2. About
me
Oleg
Tsal-‐Tsalko
Lead
So:ware
Engineer
at
EPAM
Systems.
Speaker,
acEve
member
of
Kiev
JUG.
ParEcipate
in
different
educaEonal
iniEaEves
and
JCP/AdoptJSR
programs.
3. Stream
API
-‐ An
abstracEon
that
supports
bulk
operaEons
over
sequence
of
elements
-‐ Not
a
data
structure
-‐ Simple
and
logical
chaining
of
operaEons
-‐ Lazy
evaluaEon
-‐ Internal
parallelism
if
required
-‐ Concept
of
funcEonal
programming
in
Java
5. How
can
I
get
a
Stream
to
work
with?
• CollecEon.stream()
• IntStream.range()
• Stream.of()
• Arrays.stream()
• BufferedReader.lines()
• CharSequence.chars()
• Pa`ern.splitAsStream()
6. Internal
iteraEon
over
external
Is
there
signifficant
difference?
for
(Item
item
:
items){
process(item);
}
items.forEach(item
-‐>
process(item));
7. Lambda
expressions
A
lambda
expression
is
an
anonymous
funcEon
–
Has
an
argument
list,
a
return
type,
and
a
body
(Object
o)
-‐>
o.toString()
–
A
method
reference
is
a
reference
to
an
exisEng
method
Object::toString
–
Lambdas
can
refer
to
(capture)
values
from
the
enclosing
lexical
scope
(Person
p)
-‐>p.getName().equals(name)
–
Compiler
can
o:en
infer
argument
types
from
context
p
-‐>
p.getName().equals(name)
–
Can
be
used
whenever/wherever
you
use
anonymous
classes
with
single
method
You
can
now
pass
behavior
as
a
data
between
your
objects
8. Using
lambdas
FileFilter x = new FileFilter() {
public boolean accept(File f) {
return f.canRead();
}
};
FileFilter x = (File f) -> f.canRead();
FileFilter x = File::canRead;
9. What’s
your
type?
Since
Java
doesn’t
have
FuncEon
type
on
it’s
own
Lambda’s
type
evaluated
to
some
FuncEonal
interface:
Runnable
r
=
()
-‐>
{
doSmth();
};
Callable
c
=
()
-‐>
calcResult();
Comparator
comp
=
(o1,
o2)
-‐>
compare(o1,
o2);
10. FuncEonal
interfaces
java.u&l.func&on
Package:
Predicate<T>
Determine
if
the
input
of
type
T
matches
some
criteria
Consumer<T>
Accept
a
single
input
argumentof
type
T,
and
return
no
result
Function<T, R>
Apply
a
funcEon
to
the
input
type
T,
generaEng
a
result
of
type
R
java.u&l.stream
Package:
Collector<T, A, R>
Used
to
collect
stream
of
elements
of
type
T
into
single
result
of
type
R
Collectors
Contains
number
of
predefined
Collectors
13. InstrucEons
• Download
test
project
from
GitHub:
h`ps://github.com/olegts/LambdasHacking
• Import
it
in
your
favorite
IDE
(IDEA*)
with
JDK8.
• Open
single
Exercises
class.
• Fix
as
much
tests
as
you
can
going
one
by
one
removing
@Ignore
annotaEon
and
coding
up
TODOs.