This document contains the slides for a presentation on Java 8 Lambdas and Streams. The presentation will cover lambdas, including their concept, syntax, functional interfaces, variable capture, method references, and default methods. It will also cover streams. The slides provide some incomplete definitions that will be completed during the presentation. Questions from attendees are welcome. A quick survey asks about past experience with lambdas and streams.
Slides for a lightning talk on Java 8 lambda expressions I gave at the Near Infinity (www.nearinfinity.com) 2013 spring conference.
The associated sample code is on GitHub at https://github.com/sleberknight/java8-lambda-samples
Presentation provides introduction and detailed explanation of the Java 8 Lambda and Streams. Lambda covers with Method references, default methods and Streams covers with stream operations,types of streams, collectors. Also streams are elaborated with parallel streams and benchmarking comparison of sequential and parallel streams.
Additional slides are covered with Optional, Splitators, certain projects based on lambda and streams
Java is Object Oriented Programming. Java 8 is the latest version of the Java which is used by many companies for the development in many areas. Mobile, Web, Standalone applications.
Slides for a lightning talk on Java 8 lambda expressions I gave at the Near Infinity (www.nearinfinity.com) 2013 spring conference.
The associated sample code is on GitHub at https://github.com/sleberknight/java8-lambda-samples
Presentation provides introduction and detailed explanation of the Java 8 Lambda and Streams. Lambda covers with Method references, default methods and Streams covers with stream operations,types of streams, collectors. Also streams are elaborated with parallel streams and benchmarking comparison of sequential and parallel streams.
Additional slides are covered with Optional, Splitators, certain projects based on lambda and streams
Java is Object Oriented Programming. Java 8 is the latest version of the Java which is used by many companies for the development in many areas. Mobile, Web, Standalone applications.
Java 8 is coming soon. In this presentation I have outlined the major Java 8 features. You get information about interface improvements, functional interfaces, method references, lambdas, java.util.function, java.util.stream
**** Java Certification Training: https://www.edureka.co/java-j2ee-soa-training ****
This Edureka tutorial on “Lambda Expressions in Java” will introduce you to a new Java feature called Lambda Expressions. It will also talk about the functional interface in Java. Through this tutorial you will learn the following topics:
Java Lambda Expressions
Functional Interface
Lambda Parameters
Lambda as an Object
Lambda Value Capture
Method References as lambdas
Check out our Java Tutorial blog series: https://goo.gl/osrGrS
Check out our complete Youtube playlist here: https://goo.gl/gMFLx3
Start programming in a more functional style in Java. This is the second in a two part series on lambdas and streams in Java 8 presented at the JoziJug.
In Java 8, the java.util.function has numerous built-in interfaces. Other packages in the Java library (notably java.util.stream package) make use of the interfaces defined in this package. Java 8 developers should be familiar with using key interfaces provided in this package. This presentation provides an overview of four key functional interfaces (Consumer, Supplier, Function, and Predicate) provided in this package.
This is a basic tutorial on Spring core.
Best viewed when animations and transitions are supported, e.g., view in MS Powerpoint. So, please try to view it with animation else the main purpose of this presentation will be defeated.
Spring Data is a high level SpringSource project whose purpose is to unify and ease the access to different kinds of persistence stores, both relational database systems and NoSQL data stores.
In this Meetup Victor Perepelitsky - R&D Technical Leader at LivePerson leading the 'Real Time Event Processing Platform' team , will talk about Java 8', 'Stream API', 'Lambda', and 'Method reference'.
Victor will clarify what functional programming is and how can you use java 8 in order to create better software.
Victor will also cover some pain points that Java 8 did not solve regarding functionality and see how you can work around it.
Java 8 is coming soon. In this presentation I have outlined the major Java 8 features. You get information about interface improvements, functional interfaces, method references, lambdas, java.util.function, java.util.stream
**** Java Certification Training: https://www.edureka.co/java-j2ee-soa-training ****
This Edureka tutorial on “Lambda Expressions in Java” will introduce you to a new Java feature called Lambda Expressions. It will also talk about the functional interface in Java. Through this tutorial you will learn the following topics:
Java Lambda Expressions
Functional Interface
Lambda Parameters
Lambda as an Object
Lambda Value Capture
Method References as lambdas
Check out our Java Tutorial blog series: https://goo.gl/osrGrS
Check out our complete Youtube playlist here: https://goo.gl/gMFLx3
Start programming in a more functional style in Java. This is the second in a two part series on lambdas and streams in Java 8 presented at the JoziJug.
In Java 8, the java.util.function has numerous built-in interfaces. Other packages in the Java library (notably java.util.stream package) make use of the interfaces defined in this package. Java 8 developers should be familiar with using key interfaces provided in this package. This presentation provides an overview of four key functional interfaces (Consumer, Supplier, Function, and Predicate) provided in this package.
This is a basic tutorial on Spring core.
Best viewed when animations and transitions are supported, e.g., view in MS Powerpoint. So, please try to view it with animation else the main purpose of this presentation will be defeated.
Spring Data is a high level SpringSource project whose purpose is to unify and ease the access to different kinds of persistence stores, both relational database systems and NoSQL data stores.
In this Meetup Victor Perepelitsky - R&D Technical Leader at LivePerson leading the 'Real Time Event Processing Platform' team , will talk about Java 8', 'Stream API', 'Lambda', and 'Method reference'.
Victor will clarify what functional programming is and how can you use java 8 in order to create better software.
Victor will also cover some pain points that Java 8 did not solve regarding functionality and see how you can work around it.
An introduction to the Java Platform Module System (JPMS). This talk is from April 2017, before the Java SE 9 release, so the final details may be subtly different, particularly once a standard becomes established for module names.
Aim of this presentation is not to make you masters in Java 8 Concurrency, but to help you guide towards that goal. Sometimes it helps just to know that there is some API that might be suitable for a particular situation. Make use of the pointers given to search more and learn more on those topics. Refer to books, Java API Documentation, Blogs etc. to learn more. Examples and demos for all cases discussed will be added to my blog www.javajee.com.
Java9 Beyond Modularity - Java 9 más allá de la modularidadDavid Gómez García
These are the slides I used for my "Java 9 beyond modularity" at several different local meetups and conferences in Spain during 2017
Java 9 is about to reach its public release scheduled for September 2017. If we ask what are the new features that this new version will include, probably the first that comes to our head is modularity.
But java 9 brings with a lot of features beyound Jigsaw, JPMS or modularity. In this talk we will talk about at least 9 other new features that include this new version of Java that are interesting and maybe will end up being more used than the modularity itself for those who embrace the new version.
Those are changes that come to complement and improve even more the set of new tools (like Streams, Optionals, etc...) that Java 8 brought to us.
We'll take a look at small changes in language syntax (such as new ways of using try-with-resources), changes in Collections APIs and Streams, new tools like VarHandles, new APIs such as the Flow API, and As we allow the inclusion of reactive programming with Java.
Do you want to see in Java 9 beyond modularity? Do you want to have a more complete view of what you can provide? Let's take a look toghether!
Java 8 Stream API. A different way to process collections.David Gómez García
A look on one of the features of Java 8 hidden behind the lambdas. A different way to iterate Collections. You'll never see the Collecions the same way.
These are the slides I used on my talk at the "Tech Thursday" by Oracle in June in Madrid.
This is a beginner's guide to Java 8 Lambdas, accompnied with executable code examples which you can find at https://github.com/manvendrasinghkadam/java8streams. Java 8 Streams are based on Lambdas, so this presentation assumes you know Lambdas quite well. If don't then please let me know I'll create another presentation regarding it with code examples. Lambdas are relatively easy to use and with the power of stream api you can do functional programming in Java right from start. This is very cool to be a Java programmer now.
Java 9 Modules: The Duke Yet Lives That OSGi Shall DeposeNikita Lipsky
Modules appear in Java 9 at last, but why? After all, OSGi has been around for more than 15 years and serves as the foundation of many desktop, server, and IoT applications. Its authors state that OSGi solves various dependency management problems in the most powerful way - at run time.
In this session, we will explore the problems that OSGi tries to solve, understand its approach, and identify its failures. Then we will figure out which of those problems the authors of Jigsaw ignored (and why), and which ones they solved (and how). Finally, we will talk about the challenges that Jigsaw brings with itself to the Java ecosystem and what we the developers have to do about them.
https://2017.javazone.no/program/83eb9ed50ba74946ad418a3abea0467a
The slides from the talk I gave at Oracle III #JuevesTecnológicos in Madrid.
A review of how the ParallelStreams Work in Java 8 and some considerations we must know in order to get the better performance from the concurrent data processing in #Java8
Cover Basic concept for Functional Programming in Java. Define new functional interfaces, lambda expressions, how to translate lambda expression, JVM deal with new byte code etc. This is not the perfect slides for functional programming, but trying cover simple basic functional programming.
20 minute lightning talk I gave at the May 2014 NEJUG meeting on what's new in Java 8. Citations for the code examples and images are available in the downloadable presentation and are linked indirectly via the References page.
Accelerate your Kubernetes clusters with Varnish CachingThijs Feryn
A presentation about the usage and availability of Varnish on Kubernetes. This talk explores the capabilities of Varnish caching and shows how to use the Varnish Helm chart to deploy it to Kubernetes.
This presentation was delivered at K8SUG Singapore. See https://feryn.eu/presentations/accelerate-your-kubernetes-clusters-with-varnish-caching-k8sug-singapore-28-2024 for more details.
LF Energy Webinar: Electrical Grid Modelling and Simulation Through PowSyBl -...DanBrown980551
Do you want to learn how to model and simulate an electrical network from scratch in under an hour?
Then welcome to this PowSyBl workshop, hosted by Rte, the French Transmission System Operator (TSO)!
During the webinar, you will discover the PowSyBl ecosystem as well as handle and study an electrical network through an interactive Python notebook.
PowSyBl is an open source project hosted by LF Energy, which offers a comprehensive set of features for electrical grid modelling and simulation. Among other advanced features, PowSyBl provides:
- A fully editable and extendable library for grid component modelling;
- Visualization tools to display your network;
- Grid simulation tools, such as power flows, security analyses (with or without remedial actions) and sensitivity analyses;
The framework is mostly written in Java, with a Python binding so that Python developers can access PowSyBl functionalities as well.
What you will learn during the webinar:
- For beginners: discover PowSyBl's functionalities through a quick general presentation and the notebook, without needing any expert coding skills;
- For advanced developers: master the skills to efficiently apply PowSyBl functionalities to your real-world scenarios.
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Securing your Kubernetes cluster_ a step-by-step guide to success !KatiaHIMEUR1
Today, after several years of existence, an extremely active community and an ultra-dynamic ecosystem, Kubernetes has established itself as the de facto standard in container orchestration. Thanks to a wide range of managed services, it has never been so easy to set up a ready-to-use Kubernetes cluster.
However, this ease of use means that the subject of security in Kubernetes is often left for later, or even neglected. This exposes companies to significant risks.
In this talk, I'll show you step-by-step how to secure your Kubernetes cluster for greater peace of mind and reliability.
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
Here is something new! In our next Connector Corner webinar, we will demonstrate how you can use a single workflow to:
Create a campaign using Mailchimp with merge tags/fields
Send an interactive Slack channel message (using buttons)
Have the message received by managers and peers along with a test email for review
But there’s more:
In a second workflow supporting the same use case, you’ll see:
Your campaign sent to target colleagues for approval
If the “Approve” button is clicked, a Jira/Zendesk ticket is created for the marketing design team
But—if the “Reject” button is pushed, colleagues will be alerted via Slack message
Join us to learn more about this new, human-in-the-loop capability, brought to you by Integration Service connectors.
And...
Speakers:
Akshay Agnihotri, Product Manager
Charlie Greenberg, Host
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Tobias Schneck
As AI technology is pushing into IT I was wondering myself, as an “infrastructure container kubernetes guy”, how get this fancy AI technology get managed from an infrastructure operational view? Is it possible to apply our lovely cloud native principals as well? What benefit’s both technologies could bring to each other?
Let me take this questions and provide you a short journey through existing deployment models and use cases for AI software. On practical examples, we discuss what cloud/on-premise strategy we may need for applying it to our own infrastructure to get it to work from an enterprise perspective. I want to give an overview about infrastructure requirements and technologies, what could be beneficial or limiting your AI use cases in an enterprise environment. An interactive Demo will give you some insides, what approaches I got already working for real.
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...UiPathCommunity
💥 Speed, accuracy, and scaling – discover the superpowers of GenAI in action with UiPath Document Understanding and Communications Mining™:
See how to accelerate model training and optimize model performance with active learning
Learn about the latest enhancements to out-of-the-box document processing – with little to no training required
Get an exclusive demo of the new family of UiPath LLMs – GenAI models specialized for processing different types of documents and messages
This is a hands-on session specifically designed for automation developers and AI enthusiasts seeking to enhance their knowledge in leveraging the latest intelligent document processing capabilities offered by UiPath.
Speakers:
👨🏫 Andras Palfi, Senior Product Manager, UiPath
👩🏫 Lenka Dulovicova, Product Program Manager, UiPath
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
2. The
Plan
• Lambdas
• Break
• Streams
Some
of
the
early
slides
will
provide
incomplete
definiAons
which
will
be
completed
by
the
end
of
the
presentaAon!
4. Quick
Survey
• Raise
your
hand
if
you
have
programmed
using
lambda
expressions
in
the
past
• Raise
your
hand
if
you
have
programmed
with
streams
in
the
past
6. Lambda
History
• The
mathemaAcal
theory
of
lambda
calculus
was
developed
in
the
1930s
by
Alonzo
Church
• It
found
its
way
into
programming
languages
in
the
1960s
• Most
major
programming
languages
have
support
for
lambda
expressions
including
C++,
C#,
JavaScript,
Python,
Ruby
…
etc
• We
finally
have
lambda
expressions
in
the
Java
programming
language
7. Lambda
DefiniAon
• Define
anonymous
funcAons
• Can
be
assigned
to
variables
• Can
be
passed
to
funcAons
• Can
be
returned
from
funcAons
8. What
are
lambdas
good
for
• Form
the
basis
of
the
funcAonal
programming
paradigm
• Make
parallel
programming
easier
• Write
more
compact
code
• Richer
data
structure
collecAons
• Develop
cleaner
APIs
9. Concept
vs.
ImplementaAon
• A
concept
can
have
mulAple
implementaAons
– Map
concept
implemented
by
HashMap,
ConcurrentHashMap
– List
concept
implemented
by
ArrayList,
LinkedList,
SkipList
• Lambdas
are
a
concept
that
has
its
own
implementaAon
flavor
in
different
languages
• There
are
two
disAnct
things
to
learn
– The
general
concept
of
lambdas
expressions
– The
Java
8
implementaAon
of
lambda
expressions
10. Learning
Tip
If
this
is
your
first
encounter
with
Lambda
expressions
recognize
that
the
learning
curve
associated
with
lambdas
will
be
steeper
for
you
than
for
some
one
who
has
already
learned
lambda
expressions
in
another
programming
language.
12. Print
a
list
of
integers
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
integers.forEach(
x -> System.out.println(x)
);
Output:
1
2
3
4
5
forEach is
a
method
that
accepts
a
funcAon
as
its
input
and
calls
the
funcAon
for
each
value
in
the
list
x -> System.out.println(x)
is
lambda
expression
that
defines
an
anonymous
funcAon
with
one
parameter
named
x
of
type
Integer.
13. MulA
line
Lambda
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
integers.forEach(x -> {
x = x + 10;
System.out.println(x);
});
Output:
11
12
13
14
15
14. Lambda
with
a
Local
Variable
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
integers.forEach((x) -> {
int y = x / 2;
System.out.println(y);
});
Output:
0
1
1
2
2
16. Lambda
Expression
Lifecycle
• Think
of
a
lambda
expression
as
having
a
two
stage
lifecycle.
– Convert
the
lambda
expression
to
a
funcAon
– Call
the
generated
funcAon
x -> System.out.print(x);
public static void generatedNameOfLambdaFunction(Integer x){
System.out.println(x);
}
17. Type
of
a
Lambda
Expression
• Many
programming
languages
define
a
funcAon
data
type
to
represent
lambda
expressions
• Java
8
designers
considered
adding
a
funcAon
data
type
to
Java
8
but
rejected
it
because
it
was
infeasible
for
a
variety
of
reasons
– Watch
Lambda:
A
peek
under
the
Hood
by
Brian
Goetz
for
the
details
hdp://goo.gl/PEDYWi
18. ImplementaAon
Problems
• What
class
should
the
translated
lambda
expression
funcAon
be
placed
in?
• How
are
instances
of
this
class
created?
• Should
the
generated
method
be
a
staAc
or
instance
method?
x -> System.out.print(x);
public static void generatedNameOfLambdaFunction(Integer x){
System.out.println(x);
}
20. FuncAonal
Interface
• A
funcAonal
interface
is
a
regular
Java
interface
with
a
single
method
• This
is
a
common
idiom
in
exisAng
Java
code
public interface Consumer<T> {
void accept(T t);
}
21. JDK
FuncAonal
Interfaces
public interface Runnable {
public abstract void run();
}
public interface Comparable<T> {
public int compareTo(T o);
}
public interface Callable<V> {
V call() throws Exception;
}
22. Spring
FuncAonal
Interfaces
public interface TransactionCallback<T> {
T doInTransaction(TransactionStatus status);
}
public interface RowMapper<T> {
T mapRow(ResultSet rs, int rowNum) throws SQLException;
}
public interface StatementCallback<T> {
T doInStatement(Statement stmt) throws SQLException,
DataAccessException;
}
23. Assign
Lambda
to
a
local
variable
public interface Consumer<T> {
void accept(T t);
}
void forEach(Consumer<Integer> action) {
for (Integer i : items) {
action.accept(t);
}
}
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
Consumer<Integer> consumer = x -> System.out.print(x);
integers.forEach(consumer);
• The
type
of
a
lambda
expression
is
same
as
the
funcAonal
interface
that
the
lambda
expression
is
assigned
to!
25. @FuncAonalInterface
@FunctionalInterface
public interface PasswordEncoder {
public String encode(String password, String salt);
}
• @FuncAonalInterface
causes
the
Java
8
complier
to
produce
an
error
if
the
interface
has
more
than
one
method
26. @FuncAonalInterface
@FunctionalInterface
public interface PasswordEncoder {
public String encode(String password, String salt);
public String doSomethingElse();
}
• Produces
a
complier
error
Invalid
@Func6onalInterface
annota1on;
PasswordEncoder
is
not
a
func1onal
interface
• @FuncAonalInterface
is
an
opAonal
annotaAon.
27. Lambda
&
Backward
CompaAbility
• Any
interface
with
one
method
is
considered
a
funcAonal
interface
by
Java
8
even
if
was
complied
it
with
a
Java
1.0
complier
• Java
8
lambdas
will
work
with
older
libraries
that
use
funcAonal
interfaces
without
any
need
to
recompile
or
modify
old
libraries.
28. Backward
CompaAbility
Example
JdbcTemplate template = getTemplate();
List<Product> products = template.query("SELECT * from products",
new RowMapper<Product>(){
@Override
public Product mapRow(ResultSet rs, int rowNum) throws
SQLException {
Integer id = rs.getInt("id");
String description = rs.getString("description");
Integer quantity = rs.getInt("quantity");
BigDecimal price = rs.getBigDecimal("price");
Date availability = rs.getDate("available_date");
Product product = new Product();
product.setId(id);
product.setDescription(description);
product.setQuantity(quantity);
product.setPrice(price);
product.setAvailability(availability);
return product;
}
});
29. Backward
CompaAbility
Example
JdbcTemplate template = getTemplate();
List<Product> products = template.query("SELECT * from products",
(ResultSet rs, int rowNum) -> {
Integer id = rs.getInt("id");
String description = rs.getString("description");
Integer quantity = rs.getInt("quantity");
BigDecimal price = rs.getBigDecimal("price");
Date availability = rs.getDate("available_date");
Product product = new Product();
product.setId(id);
product.setDescription(description);
product.setQuantity(quantity);
product.setPrice(price);
product.setAvailability(availability);
return product;
});
30. Is
this
clear?
QuesAons?
@FunctionalInterface
public interface PasswordEncoder {
public String encode(String password, String salt);
}
public PasswordEncoder makeBadEncoder() {
return (password, salt) -> password.toUpperCase();
}
public void doSomething(PasswordEncoder encoder) {
String salted = encoder.encode("abc", "123");
}
PasswordEncoder encoder = makeBadEncoder();
doSomething(encoder);
31. Summary
Please
Read
…
• A
funcAonal
interface
is
an
interface
with
a
single
method
(incomplete
definiAon)
• The
method
generated
from
a
lambda
8
expression
must
have
the
same
signature
as
the
method
in
the
funcAonal
interface
• In
Java
8
the
type
of
a
Lambda
expression
is
the
same
as
the
the
funcAonal
interface
that
the
lambda
expression
is
assigned
to.
33. Variable
Capture
• Lambdas
can
interact
with
variables
defined
outside
the
body
of
the
lambda
• Using
variables
outside
the
body
of
a
lambda
expression
is
called
variable
capture
34. Capture
a
local
variable
public class LambdaCaptureExample {
public static void main(String[] args) {
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
int var = 10;
integers.forEach(x -> System.out.println(x + var));
}
}
Output:
11
12
13
14
15
35. EffecAvely
Final
public class LambdaCaptureExample {
public static void main(String[] args) {
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
int var = 1;
integers.forEach(x -> {
var++;
Error:
Local
variable
var
defined
in
an
enclosing
scope
must
be
final
or
effecAvely
final
System.out.println(x);
});
}
}
• Local
variables
used
inside
the
body
of
a
lambda
must
be
declared
final
or
the
compiler
must
be
able
to
tell
that
they
are
effecAvely
final
because
their
value
is
not
modified
elsewhere
36. EffecAvely
Final
public class LambdaCaptureExample {
public static void main(String[] args) {
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
int var = 1;
integers.forEach(x -> System.out.println(x + var));
Error:
Local
variable
var
defined
in
an
enclosing
scope
must
be
final
or
effecAvely
final
var = 50;
}
}
37. Capture
StaAc
Variables
public class LambdaCaptureExample {
private static int var = 1;
public static void main(String[] args) {
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
integers.forEach(x -> System.out.println(x + var));
}
}
38. Capture
Class
Variables
public class LambdaCaptureExample {
private int var = 1;
private List<Integer> integers = Arrays.asList(1,2,3,4,5);
private void doSomething() {
integers.forEach(x -> System.out.println(x + var));
}
public static void main(String[] args) {
new LambdaCaptureExample5().doSomething();
}
}
39. this
within
a
lambda
body
public class Example {
private static final Example INSTANCE = new Example();
private int var = 1;
private List<Integer> integers = Arrays.asList(1,2,3,4,5);
public void doSomething() {
integers.forEach(x -> {
System.out.println(x + this.var);
if (this == INSTANCE) {
System.out.println("Within the lambda body this refers to the this of the
enclosing object");
}
});
}
public static void main(String[] args) {
INSTANCE.doSomething();
}
}
40. This
within
a
anonymous
Inner
class
public class Example {
private static final Example INSTANCE = new Example();
private int var = 1;
private List<Integer> integers = Arrays.asList(1,2,3,4,5);
public void doSomething() {
integers.forEach( new Consumer<Integer>(){
private int state=10;
@Override
public void accept(Integer x) {
int y = this.state + Example.this.var + x;
System.out.println("Anonymous class " + y);
}
});
}
public static void main(String[] args) {
INSTANCE.doSomething();
}
}
41. Lambda
vs.
Anonymous
Inner
Class
• Inner
classes
can
have
state
in
the
form
of
class
level
instance
variables
lambdas
can
not
• Inner
classes
can
have
mulAple
methods
lambdas
only
have
a
single
method
body
• this
points
to
the
object
instance
for
an
anonymous
Inner
class
but
points
to
the
enclosing
object
for
a
lambda
• Lambda
!=
Anonymous
inner
class
42. java.uAl.funcAon.*
• java.u1l.func1on
package
contains
43
commonly
used
funcAonal
interfaces
– Consumer<T>
-‐
funcAon
that
takes
an
argument
of
type
T
and
returns
void
– Supplier<T>
-‐
funcAon
that
takes
no
argument
and
returns
a
result
of
Type
T
– Predicate<T>
-‐
funcAon
that
takes
an
argument
of
type
T
and
returns
a
boolean
– Func1on<T,
R>
-‐
funcAon
that
takes
an
argument
of
Type
T
and
returns
a
result
of
type
R
– …
etc
44. Method
References
• A
lambda
is
a
way
to
define
an
anonymous
funcAon
• But
what
if
the
funcAon
that
we
want
to
use
is
already
wriden
• Method
references
can
be
used
to
pass
an
exisAng
funcAon
in
place
where
a
lambda
is
expected
45. Reference
a
staAc
method
public class Example {
public static void doSomething(Integer i)
{
System.out.println(i);
}
public static void main(String[] args) {
Consumer<Integer> conusmer1 = x -> doSomething(x);
conusmer1.accept(1); // 1
Consumer<Integer> conusmer2 = Example::doSomething;
conusmer2.accept(1); // 1
}
}
The
signature
of
the
referenced
method
needs
to
match
the
signature
of
funcAonal
interface
method
46. Reference
a
constructor
• Constructor
methods
references
are
quite
handy
when
working
with
streams.
Function<String, Integer> mapper1 = x -> new Integer(x);
System.out.println(mapper1.apply("11")); // new Integer(11)
Function<String, Integer> mapper2 = Integer::new; System.out.println
(mapper2.apply("11")); // new Integer(11)
47. references
to
a
specific
object
instance
method
Consumer<Integer> conusmer1 = x -> System.out.println(x);
conusmer1.accept(1); // 1
Consumer<Integer> conusmer2 = System.out::println;
conusmer2.accept(1); // 1
• System.out::println
method
reference
tells
the
compiler
that
the
lambda
body
signature
should
match
the
method
println
and
that
the
lambda
expression
should
result
in
a
call
to
System.out.println(x)
48. Instance
method
references
to
arbitrary
object
of
a
parAcular
type
Function<String, String> mapper1 = x -> x.toUpperCase();
System.out.println(mapper1.apply("abc")); // ABC
Function<String, String> mapper2 = String::toUpperCase; System.out.println
(mapper2.apply("def")); // DEF
• Invoked
on
an
object
passed
as
input
to
the
lambda
49. Method
References
Summary
Method
Reference
Type
Syntax
Example
StaAc
ClassName::StaAcMethodName
String::valueOf
Constructor
ClassName::new
String::new
Specific
object
instance
objectReference::MethodName
System.out::println
Arbitrary
object
of
a
parAcular
type
ClassName::InstanceMethodName
String::toUpperCase
51. The
interface
evoluAon
problem!
• A
natural
place
to
use
lambdas
is
with
the
Java
collecAons
framework
• The
collecAon
framework
is
defined
with
interfaces
such
as
Iterable,
CollecAon,
Map,
List,
Set,
…
etc.
• Adding
a
new
method
such
forEach
to
the
Iterable
interface
will
mean
that
all
exisAng
implementaAons
of
Iterable
will
break
• How
can
published
interfaces
be
evolved
without
breaking
exisAng
implementaAons!
52. default
Method
• A
default
method
on
java
interface
has
an
implementaAon
provided
in
the
interface
and
is
inherited
by
classes
that
implement
the
interface.
public interface Iterable<T> {
Iterator<T> iterator();
default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}
default Spliterator<T> spliterator() {
return Spliterators.spliteratorUnknownSize(iterator(), 0);
}
}
53. default
method
inheritance
public interface Test {
default void doSomething()
{
System.out.println("Test");
}
}
public class TestImpl implements Test {
public static void main(String[] args) {
TestImpl1 testImpl = new TestImpl1();
testImpl.doSomething(); // Test
}
}
54. Overriding
a
default
method
public interface Test {
default void doSomething()
{
System.out.println("Test");
}
}
public class TestImpl implements Test {
@Override
public void doSomething() {
System.out.println("TestImpl");
}
public static void main(String[] args) {
TestImpl testImpl = new TestImpl();
testImpl.doSomething(); // TestImpl
}
}
55. A
hierarchy
of
default
methods
public interface Test {
default void doSomething(){
System.out.println("Test");
}
}
public interface TestA extends Test {
@Override
default void doSomething()
{
System.out.println("TestA");
}
}
public class TestImpl implements TestA {
public static void main(String[] args) {
TestImpl testImpl = new TestImpl();
testImpl.doSomething(); // TestA
}
}
56. default
method
conflict
public interface A {
default void doSomething() {
System.out.println("A");
}
}
public class ABImpl implements A, B {
}
public interface B {
default void doSomething() {
System.out.println(“B");
}
}
Compile
Error:
Duplicate
default
methods
named
doSomething
with
the
parameters
()
and
()
are
inherited
from
the
types
B
and
A
57. Resolving
default
method
conflict
public interface A {
default void doSomething() {
System.out.println("A");
}
}
public class ABImpl implements A, B {
@Override
public void doSomething() {
System.out.println("ABImpl");
A.super.doSomething(); // notice A.super syntax
}
public static void main(String[] args) {
new ABImpl2().doSomething(); // ABImpl n A
}
}
public interface B {
default void doSomething() {
System.out.println(“B");
}
}
58. Diamonds
are
No
Problem
public interface A {
default void doSomething() {
System.out.println("A");
}
}
public class CDImpl implements C, D {
public static void main(String[] args) {
new CDImpl().doSomething();
}
}
Outputs : D
public interface C extends A {
default void other() {
System.out.println("C");
}
}
public interface D extends A {
@Override
default void doSomething(){
System.out.println("D");
}
}
59. default
method
Summary
• A
default
method
on
an
interface
can
have
an
implementaAon
body
• if
there
is
a
conflict
between
default
methods
the
class
that
is
implemenAng
the
default
methods
must
override
the
conflicAng
default
method
• In
an
inheritance
hierarchy
with
default
methods
the
most
specific
default
method
wins.
61. Are
these
concepts
clear?
• Lambda
expression
• FuncAonal
interface
• Method
reference
• Default
method
62. 5
min
break
• Start
5
minute
Count
Down
Timer
• Streams
63. CollecAons
Enhancements
• Java
8
uses
lambda
expressions
and
default
methods
to
improve
the
exisAng
java
collecAons
frameworks
• Internal
iteraAon
– delegates
the
looping
to
a
library
funcAon
such
as
forEach
and
the
loop
body
processing
to
a
lambda
expression.
– allows
the
library
funcAon
we
are
delegaAng
to
implement
the
logic
needed
to
execute
the
iteraAon
on
mulAple
cores
if
desired
64. Some
New
Methods
• New
java.lang.Iterable
methods
in
Java
8
– default
void
forEach(Consumer<?
super
T>
acAon)
– default
Spliterator<T>
spliterator()
• New
java.uAl.CollecAon
Methods
in
Java
8
– default
boolean
removeIf(Predicate<?
super
E>
filter)
– default
Spliterator<E>
spliterator()
– default
Stream<E>
stream()
– default
Stream<E>
parallelStream()
65. Some
New
Methods
….
• New
java.uAl.Map
Methods
in
Java
8
– default
V
getOrDefault(Object
key,
V
defaultValue)
–
putIfAbsent(K
key,
V
value)
– ….
etc
66. Stream
related
methods
• Common
stream
related
methods
– default
Spliterator<T>
spliterator()
– default
Stream<E>
stream()
– default
Stream<E>
parallelStream()
67. What
is
a
Stream?
• Streams
are
a
funcAonal
programming
design
padern
for
processing
sequences
of
elements
sequenAally
or
in
parallel
• When
examining
java
programs
we
always
run
into
code
along
the
following
lines.
– Run
a
database
query
get
a
list
of
objects
– Iterate
over
the
list
to
compute
a
single
result
– Iterate
over
the
list
to
generate
a
new
data
structure
another
list,
map,
set
or
…
etc.
• Streams
are
a
concept
that
can
be
implemented
in
many
programming
languages
68. Java
8
Streams
• Create
a
stream
instance
from
a
source
java
collecAon
• Add
a
filter
operaAon
to
the
stream
intermediate
opera1ons
pipeline
• Add
a
map
operaAon
to
to
the
stream
intermediate
opera1ons
pipeline
• Add
a
terminal
opera1on
that
kicks
off
the
stream
processing
List<Order> orders = getOrders();
int totalQuantity = orders.stream()
.filter(o -> o.getType() == ONLINE)
.mapToInt(o -> o.getQuantity())
.sum();
69. Stream
Structure
• A
stream
has
a
– source
that
the
stream
can
pull
objects
from
– pipeline
of
operaAons
that
will
execute
on
the
elements
of
the
stream
– terminal
operaAon
that
pulls
values
down
the
stream
Source
Pipeline
Terminal
70. Stream
lifecycle
• Crea1on
Streams
get
created
from
a
source
object
such
as
a
collecAon,
file,
or
generator
• Configura1on
Streams
get
configured
with
a
collecAon
of
pipeline
operaAons.
• Execu1on
Stream
terminal
operaAon
is
invoked
which
starts
pulling
objects
trough
the
operaAons
pipeline
of
the
stream.
• Cleanup
Stream
can
only
be
used
once
and
have
a
close()
method
which
needs
to
be
called
if
the
stream
is
backed
by
a
IO
source
Create
Config
Execute
Cleanup
71. Number
Stream
Source
System.out.println("Long Stream Source");
LongStream.range(0, 5)
.forEach(System.out::println);
Output:
Long
Stream
Source
0
1
2
3
4
72. CollecAon
Stream
Source
List<String> cities = Arrays.asList("toronto",
"ottawa”,"montreal","vancouver");
cities.stream()
.forEach(System.out::println);
Output:
toronto
odawa
montreal
vancouver
73. Character
Stream
Source
long length = "ABC".chars().count(); // <1>
System.out.println(length);
Output:
3
78. Stream
Terminal
OperaAons
• Reduc1on
Terminal
Opera1ons — return
a
single
result
• Mutable
Reduc1on
Terminal
Opera1ons —
return
mulAple
results
in
a
container
data
structure
• Search
Terminal
Opera1ons — return
a
result
as
soon
as
a
match
is
found
• Generic
Terminal
Opera1on
— do
any
kind
of
processing
you
want
on
each
stream
element
• Nothing
happens
unAl
the
terminal
operaAon
is
invoked!
79. ReducAon
Terminal
OperaAons
List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
Long count = integers.stream().count();
System.out.println(count); // 5
Optional<Integer> result;
result = integers.stream().min( (x, y) -> x – y);
System.out.println(result.get()) // 1
result = integers.stream().
max(Comparator.comparingInt(x -> x));
System.out.println(result.get()); // 5
Integer result = integers.stream().reduce(0,(x,y) -> x + y)
System.out.println(result); // 15
83. Streams
Pipeline
Rules
• Streams
can
process
elements
sequenAally
• Streams
can
process
elements
in
parallel
• Therefore
stream
operaAons
are
not
allowed
to
modify
the
stream
source
84. Intermediate
Stream
OperaAons
• Stateless
intermediate
opera1ons — do
not
need
to
know
the
history
of
results
from
the
previous
steps
in
the
pipeline
or
keep
track
of
how
many
results
it
have
produced
or
seen
– filter,
map,
flatMap,
peek
• Stateful
Intermediate
Opera1ons — need
to
know
the
history
of
results
produced
by
previous
steps
in
the
pipeline
or
needs
to
keep
track
of
how
many
results
it
has
produced
or
seen
– disAnct,
limit,
skip,
sorted