Lambdas and Stream
Lambdas and Stream
Lambdas and Stream
in Java 8
STREAMS AND LAMBDAS IN JAVA 8 | © PROF. DR. DANIEL JOBST | WS 2015/16 | VERSION 1.0
1
Working Environment
- Integrated Development Environment (IDE)
- JDK 8
STREAMS AND LAMBDAS IN JAVA 8 | © PROF. DR. DANIEL JOBST | WS 2015/16 | VERSION 1.0 5
WORKING ENVIRONMENT
STREAMS AND LAMBDAS IN JAVA 8 | © PROF. DR. DANIEL JOBST | WS 2015/16 | VERSION 1.0 6
WORKING ENVIRONMENT
JVM API
java.exe
java.*
STREAMS AND LAMBDAS IN JAVA 8 | © PROF. DR. DANIEL JOBST | WS 2015/16 | VERSION 1.0 7
WORKING ENVIRONMENT
STREAMS AND LAMBDAS IN JAVA 8 | © PROF. DR. DANIEL JOBST | WS 2015/16 | VERSION 1.0 8
Basics Revisited
- Interfaces
- Collections Framework
- Anonymous Inner Classes
STREAMS AND LAMBDAS IN JAVA 8 | © PROF. DR. DANIEL JOBST | WS 2015/16 | VERSION 1.0 9
BASICS REVISITED
Interfaces
“Ordinary” interfaces
Marker interfaces (e.g. Serializable or Runnable)
Functional interfaces (annotated with @FunctionalInterface)
@interface classes (Annotations)
New in Java 8:
static methods
default methods
Default methods1
“A
default
method
is
a
method
that
is
declared
in
an
interface
with
the
default
modifier;
its
body
is
always
represented
by
a
block.
It
provides
a
default
implementa=on
for
any
class
that
implements
the
interface
without
overriding
the
method.
Default
methods
are
dis=nct
from
concrete
methods
(§8.4.3.1),
which
are
declared
in
classes.”
1[Gosling 2015, p. 288]
STREAMS AND LAMBDAS IN JAVA 8 | © PROF. DR. DANIEL JOBST | WS 2015/16 | VERSION 1.0 10
BASICS REVISITED
T
<<interface>>
Collec,ons
Comparable
+
<<T>>
emptySet()
:
Set<T>
Definition
STREAMS AND LAMBDAS IN JAVA 8 | © PROF. DR. DANIEL JOBST | WS 2015/16 | VERSION 1.0 11
BASICS REVISITED
Collections Framework
Two things to remember:
1. There are Lists, Sets, and Maps:
List<T>:
ArrayList<T>
or
LinkedList<T>
Set<T>:
TreeSet<T>
or
HashSet<T>
Map<K,
V>:
TreeMap<K,
V>
or
HashMap<K,
V>
2. Use “loosly coupled” references:
List<String>
=
new
ArrayList<>();
Collections Framework1
“The
collec=ons
framework
is
a
unified
architecture
for
represen=ng
and
manipula=ng
collec=ons,
enabling
them
to
be
manipulated
independently
of
the
details
of
their
representa=on.
It
reduces
programming
effort
while
increasing
performance.
[…]”
1[Oracle Corp. 2016]
STREAMS AND LAMBDAS IN JAVA 8 | © PROF. DR. DANIEL JOBST | WS 2015/16 | VERSION 1.0 12
BASICS REVISITED
<<interface>>
E
E
<<interface>>
E
<<interface>>
E
<<interface>>
List
Queue
Set
SortedSet
<<interface>>
<<interface>>
E
Deque
NavigableSet
E
AbstractCollec,on
E
T
AbstractSet
AbstractList
E
AbstractSequen,alList
E
E
E
E
E
ArrayList
Vector
LinkedList
HashSet
TreeSet
STREAMS AND LAMBDAS IN JAVA 8 | © PROF. DR. DANIEL JOBST | WS 2015/16 | VERSION 1.0 13
BASICS REVISITED
K,V
<<interface>>
K,V
<<interface>>
Map
SortedMap
T
K,V
<<interface>>
K,V
Dic,onary
AbstractMap
NavigableMap
E
K,V
K,V
E
E
Proper,es
LinkedHashMap
STREAMS AND LAMBDAS IN JAVA 8 | © PROF. DR. DANIEL JOBST | WS 2015/16 | VERSION 1.0 14
COLLECTIONS
STREAMS AND LAMBDAS IN JAVA 8 | © PROF. DR. DANIEL JOBST | WS 2015/16 | VERSION 1.0 17
Streams
STREAMS AND LAMBDAS IN JAVA 8 | © PROF. DR. DANIEL JOBST | WS 2015/16 | VERSION 1.0 18
STREAMS
Streams
A stream is “[…] a sequence of elements from a source that supports
aggregate operations”:1
STREAMS AND LAMBDAS IN JAVA 8 | © PROF. DR. DANIEL JOBST | WS 2015/16 | VERSION 1.0 19
STREAMS
Streams
§ are not data structure
§ do not contain storage for data
§ are “pipelines” for streams of data (i.e. of objects)
§ while in the pipeline data undergo transformation
(without changing the data structure holding it)
§ wrap collections (lists, set, maps)
§ read data from it
§ work on copies
STREAMS AND LAMBDAS IN JAVA 8 | © PROF. DR. DANIEL JOBST | WS 2015/16 | VERSION 1.0 20
STREAMS
STREAMS AND LAMBDAS IN JAVA 8 | © PROF. DR. DANIEL JOBST | WS 2015/16 | VERSION 1.0 21
STREAMS
STREAMS AND LAMBDAS IN JAVA 8 | © PROF. DR. DANIEL JOBST | WS 2015/16 | VERSION 1.0 22
STREAMS
Streaming example
“Take all names from the stream that start with the letter “J”, map the names
into capital letters, skip one, and collect them into a new set”
STREAMS AND LAMBDAS IN JAVA 8 | © PROF. DR. DANIEL JOBST | WS 2015/16 | VERSION 1.0 23
Lambda Expressions and
Functional Interfaces
- Lambdas
- Functional Interfaces
STREAMS AND LAMBDAS IN JAVA 8 | © PROF. DR. DANIEL JOBST | WS 2015/16 | VERSION 1.0 24
LAMBDA EXPRESSIONS
Lambdas or Closures
“Lambda” = “closure” = record storing a function (functionality,
method) and its environment (but without a class or method name)
Roughly: anonymous method
Lambdas represent source code - not data and not object state!
Syntax:
(
parameter
list
)
-‐>
{
expression(s)
}
Examples:
(int
x,
int
y)
-‐>
{
return
x
+
y;
}
STREAMS AND LAMBDAS IN JAVA 8 | © PROF. DR. DANIEL JOBST | WS 2015/16 | VERSION 1.0 25
LAMBDA EXPRESSIONS
@FunctionalInterface
public
interface
Counter<T>
{
int
count(T
obj);
}
Task: Create a first lambda expression that counts the letters within a String
Counter<String>
strCount
=
(String
s)
-‐>
{
return
s.length();
};
[https://docs.oracle.com/javase/8/docs/api/java/lang/FunctionalInterface.html]
STREAMS AND LAMBDAS IN JAVA 8 | © PROF. DR. DANIEL JOBST | WS 2015/16 | VERSION 1.0 26
LAMBDA EXPRESSIONS
Your task:
Prepare your first lambda expression
to compare two String objects by length
STREAMS AND LAMBDAS IN JAVA 8 | © PROF. DR. DANIEL JOBST | WS 2015/16 | VERSION 1.0 27
LAMBDA EXPRESSIONS
STREAMS AND LAMBDAS IN JAVA 8 | © PROF. DR. DANIEL JOBST | WS 2015/16 | VERSION 1.0 28
LAMBDA EXPRESSIONS
Type inference
Lambda expressions allow for minimal syntax if compiler can deduct
type information (so called type inference), e.g.:
@FunctionalInterface
public
interface
BiFunction<T,
U,
R>
{
R
=
Integer could be inferred from return type of
R
apply(T
t,
U
u);
expression t.length()
+
u.length()
à Integer
}
(e.g. when used directly in typed method call)
STREAMS AND LAMBDAS IN JAVA 8 | © PROF. DR. DANIEL JOBST | WS 2015/16 | VERSION 1.0 29
LAMBDA EXPRESSIONS
STREAMS AND LAMBDAS IN JAVA 8 | © PROF. DR. DANIEL JOBST | WS 2015/16 | VERSION 1.0 30
LAMBDA EXPRESSIONS
STREAMS AND LAMBDAS IN JAVA 8 | © PROF. DR. DANIEL JOBST | WS 2015/16 | VERSION 1.0 31
Streaming API
- Creating Streams
- Fluently working with streams
- Finalize Streams
STREAMS AND LAMBDAS IN JAVA 8 | © PROF. DR. DANIEL JOBST | WS 2015/16 | VERSION 1.0 32
STREAMING API
STREAMS AND LAMBDAS IN JAVA 8 | © PROF. DR. DANIEL JOBST | WS 2015/16 | VERSION 1.0 33
STREAMING API
Stream operations
Source => STREAM => OP1 => OP2 => ... => OPn => Result
STREAMS AND LAMBDAS IN JAVA 8 | © PROF. DR. DANIEL JOBST | WS 2015/16 | VERSION 1.0 34
STREAMING API
Class Optional<T>
The class Optional<T> is a container wrapped around an object and is useful
if you do not know whether its content is null or not (e.g. when using in
fluent programming style).
T
<<interface>>
Optional
+ get() : T
+ isPresent() : boolean
+ ifPresent( : Consumer<? super T> )
+ orElse( other : T ) : T
STREAMS AND LAMBDAS IN JAVA 8 | © PROF. DR. DANIEL JOBST | WS 2015/16 | VERSION 1.0 35
STREAMING API
Example
List<Transaction>
groceryTransactions
=
new
Arraylist<>();
for(Transaction
t
:
transactions){
if(t.getType()
==
Transaction.GROCERY)
{
groceryTransactions.add(t);
}
“old fashioned”
}
Collections.sort(groceryTransactions,
new
Comparator(){
@Override
public
int
compare(Transaction
t1,
Transaction
t2){
return
t2.getValue().compareTo(t1.getValue());
}
});
List<Integer>
transactionIds
=
new
ArrayList<>();
for(Transaction
t
:
groceryTransactions)
{
transactionsIds.add(t.getId());
}
List<Integer>
transactionsIds
=
Stream like
transactions.stream()
.filter(t
-‐>
t.getType()
==
Transaction.GROCERY)
.sorted(comparing(Transaction::getValue).reversed())
.map(Transaction::getId)
.collect(toList());
[taken from Urma (2014a)]
STREAMS AND LAMBDAS IN JAVA 8 | © PROF. DR. DANIEL JOBST | WS 2015/16 | VERSION 1.0 36
Bibliography
STREAMS AND LAMBDAS IN JAVA 8 | © PROF. DR. DANIEL JOBST | WS 2015/16 | VERSION 1.0 37
Gosling, J. et al. (2015): The Java® Language Specification – Java SE 8 Edition, March
2015, http://docs.oracle.com/javase/specs/jls/se8/jls8.pdf
Huges, J. (1984): Why Functional Programming Matters, rev. ed., http://
www.cse.chalmers.se/~rjmh/Papers/whyfp.pdf
Oracle Corp. (2016): The Collections Framework, Website, http://docs.oracle.com/
javase/8/docs/technotes/guides/collections/
Turner, D. (2013): Some History of Functional Programming Languages. In: Loidl, H.-
W. and Pena, R.: Trends in Functional Programming: 13th International Symposium,
TFP 2012, St. Andrews, UK, June 12-14, 2012, Revised Selected Papers, p. 1-20.
Springer: Berlin and Heidelberg
Urma, R.-G. (2014a): Processing Data with Java SE 8 Streams, Part 1, Java Magazine,
March/April 2014, http://www.oracle.com/technetwork/articles/java/ma14-‐
java-‐se-‐8-‐streams-‐2177646.html
Urma, R.-G. (2014b): Part 2: Processing Data with Java SE 8 Streams, Java Magazine,
May/June 2014, http://www.oracle.com/technetwork/articles/java/architect-‐
streams-‐pt2-‐2227132.html
STREAMS AND LAMBDAS IN JAVA 8 | © PROF. DR. DANIEL JOBST | WS 2015/16 | VERSION 1.0 38