Lambda Expressions and Java 8 Streams Jan Trienes, adapted by Th. Dorssers, Pieter van den Hombergh Contents of this talk. Introduction Definition Why Lambdas Syntax Short Forms Ad-hoc Functionality Functionality as argument Representation of Lambda Expression Functional Interfaces Type Inference Variable Binding and Scoping Variable Binding Scoping Internal/External Iteration Streams Streams? Operations on Streams Example Additional Lambda Expressions and Java 8 Streams Jan Trienes, adapted by Th. Dorssers, Pieter van den Hombergh Fontys Hogeschool voor Techniek en Logistiek February 24, 2017 Jan Trienes, adapted by Th. Dorssers, Pieter van den Hombergh/FHTenL Lambda Expressions and Java 8 Streams February 24, 2017 1/27
27
Embed
Lambda Expressions and Java 8 Streams · Java 8 Streams Jan Trienes, adapted by Th. Dorssers, Pieter van den Hombergh Contents of this talk. Introduction Definition Why Lambdas Syntax
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
DefinitionLambda expressions are basic ingredients of so the calledLambda calculus which is a formal language for describingfunctions and their definition.It makes it possible to denote functions anonymous, sowithout a name. Examples: λx .2x + 1 or λn.λm.2n + 3minstead of f (x) = 2x + 1 or h(n,m) = 2n + mProf. Freudenthal introduced the deny-x symbol for it (InDutch: ontikser)
For Java programmersLambda expressions express a piece of functionality.( i n t x ) −> { r e t u r n 2x+1; }
Jan Trienes, adapted by Th. Dorssers, Pieter van den Hombergh/FHTenL Lambda Expressions and Java 8 Streams February 24, 2017 3/27
Why LambdasA lambda expression is a block of code that you can passaround so it can be executed later, once or multiple times.We have seen this before with anonymous classes:
Anonymous class: a button callbackbutton . setOnAction (
new EventHandler<ActionEvent> ( ) {p u b l i c v o i d handle ( ActionEvent event ) {
System . out . println ( " Thanks for clicking " ) ;}
}) ;
Jan Trienes, adapted by Th. Dorssers, Pieter van den Hombergh/FHTenL Lambda Expressions and Java 8 Streams February 24, 2017 4/27
The parameter list is placed before the -> in ()(parenthesis). The lambda body follows afterwards in{} (braces).Although not obvious, a lambda expression can return avalue or throw an exception.Return type and exceptions are inferred by the compiler.The only thing that a lambda lacks, is a name.Therefore a lambda expression is sometimes calledanonymous method.
Jan Trienes, adapted by Th. Dorssers, Pieter van den Hombergh/FHTenL Lambda Expressions and Java 8 Streams February 24, 2017 6/27
1 p u b l i c s t a t i c v o i d main ( String [ ] args ) {2 ReCalc reCalc = new ReCalc ( ) ;3 i n t result ;4 // with anonymous inner class5 Calculator cAnon = new Calculator ( ) {67 @Override8 p u b l i c i n t calculate ( i n t a , i n t b ) {9 r e t u r n a + b ;
10 }11 } ;12 result = reCalc . calculate ( cAnon , 10 , 32 ) ;13 System . out . println ( result ) ;14 // with lamba expression15 result = reCalc . calculate ( ( x , y ) −> x + y , 12 , 30 ) ;16 System . out . println ( result ) ;17 //* you can use an expession as 'data ' too.18 Calculator cLambda = ( x , y ) −> x + y ;19 result = reCalc . calculate ( cLambda , 12 , 30 ) ;20 System . out . println ( result ) ;21 }
Jan Trienes, adapted by Th. Dorssers, Pieter van den Hombergh/FHTenL Lambda Expressions and Java 8 Streams February 24, 2017 8/27
Example 2Define a method to filter some input to a new list.
1 List<Person> filter ( List<Person> persons ,2 P r e d i c a t e <? s u p e r Person> filter ) {34 List<Person> result = new ArrayList ( ) ;56 f o r ( Person p : persons ) { // see also stream version7 i f ( filter . test ( p ) ) {8 result . add ( p ) ;9 }
10 }1112 r e t u r n result ;13 }1415 p u b l i c s t a t i c v o i d main ( String [ ] args ) {16 LambdaShowcase sc = new LambdaShowcase ( ) ;17 printList ( "all" , somePersons ( ) ) ;1819 List<Person> ofAge = sc . filter ( somePersons ( ) ,20 Person : : isFullAged ) ;2122 printList ( " ofAge =" , ofAge ) ;23 }
Notice line 2: See Java 8 java.util.function.Predicate
Jan Trienes, adapted by Th. Dorssers, Pieter van den Hombergh/FHTenL Lambda Expressions and Java 8 Streams February 24, 2017 9/27
Syntax Short FormsSeveral syntax variations exist:
1 // parameter type , return statement2 filter ( personList , ( Person p ) −> { r e t u r n p .←↩
isFullAged ( ) ; } ) ;3 // infered parameter type and return type.4 filter ( personList , p −> p . isFullAged ( ) ) ;5 // the last one is a method reference on p6 filter ( personList , p : : isFullAged ) ;7 // You can also write Person :: isFullAged , which ←↩
unambiguously8 // resolves to the same instance (as in non static )←↩
10 // the one below is a static method reference ...11 // ... in class Person .12 filter ( personList , Person : : hasPrimeAge ) ;
Notice that a method signature does NOT include thestatic modifier, so a method signature refers to either astatic or an instance method and is unambiguously resolved.
Jan Trienes, adapted by Th. Dorssers, Pieter van den Hombergh/FHTenL Lambda Expressions and Java 8 Streams February 24, 2017 10/27
Lambda expressions can be used where anonymousinner-classes with one method are required.They reduce the syntactical overhead.Object creation is no longer needed on programmersside. In Java methods always belong to an object. Thisholds for lambda functions (anonymous methods) aswell. Thus an object has to be created.1
1the compiler takes care of thatJan Trienes, adapted by Th. Dorssers, Pieter van den Hombergh/FHTenL Lambda Expressions and Java 8 Streams February 24, 2017 13/27
Functional InterfacesAs mentioned before, a lambda expression is of a certaintype. This type is a subtype of the so called target type.Target types of a lambda expression are declared inJava as a @FunctionalInterface, like:
@FunctionalInterfacei n t e r f a c e Calculator {
i n t calculate ( i n t n ) ;}
A functional interface is an interface with only oneabstract method.There are plenty of functional interfaces in Java. Forinstance: Runnable, Callable, ActionListener,Comparator...Lambdas are backwards compatible with an interfacewith only one single abstract method, also know asSAM for Single Abstract Method.Many functional interfaces are declared in the packagejava.util.function
Jan Trienes, adapted by Th. Dorssers, Pieter van den Hombergh/FHTenL Lambda Expressions and Java 8 Streams February 24, 2017 15/27
In the example, we never specified that the lambdaexpression is of type Calculator.The compiler resolves this with type inference.The compiler inspects the context in which the lambdaexpression is created and figures out which type isneeded.The given lambda expression is validated against thistype (does the signature2 match?).In Venlo we call the signature minus name the shape ofa method.If the shape matches, the compiler creates a sub-type ofthe target-type.
Example of a shape:i n t e r f a c e BiFunction<T , U , R> {
R apply ( T t , U u ) ;}// fits to shape( T t , U u ) −> expression of type R
2signature without name.Jan Trienes, adapted by Th. Dorssers, Pieter van den Hombergh/FHTenL Lambda Expressions and Java 8 Streams February 24, 2017 16/27
Access to enclosing contextOccasionally an anonymous inner-class or a lambdaexpression needs access to variables in the enclosing context.The mechanism to support this is called variable binding.
ScopingA anonymous inner-class and a lambda expressions differ intheir scoping.
Jan Trienes, adapted by Th. Dorssers, Pieter van den Hombergh/FHTenL Lambda Expressions and Java 8 Streams February 24, 2017 17/27
ScopingAnonymous Inner-class vs. Lambda Expressions
Own scope vs. lexical scope1 {2 i n t n = 0 ;34 Thread t = new Thread ( new Runnable ( ) {5 @Override6 p u b l i c v o i d run ( ) {7 i n t n = 0 ; // this is fine8 }9 }) ;
1011 Thread t2 = new Thread ( ( ) −> {12 i n t n ; // compiler complains , n already defined13 }) ;14 }
Jan Trienes, adapted by Th. Dorssers, Pieter van den Hombergh/FHTenL Lambda Expressions and Java 8 Streams February 24, 2017 19/27
Internal vs. External IterationThe collections framework now supports internaliterationThis is a clear separation of concerns. The “how” andthe “what” is encapsulated and independent
Consider the difference: both useList<String> names = new ArrayList <>();
External iteration
Iterator<String> it = names . iterator ( ) ;w h i l e ( it . hasNext ( ) ) {
System . out . println ( it . next ( ) ) ;}
versus
Internal iteration
names . forEach ( name −> System . out . println ( name ) ) ;
Notice: the for-each loop is the same as external iteration.Jan Trienes, adapted by Th. Dorssers, Pieter van den Hombergh/FHTenL Lambda Expressions and Java 8 Streams February 24, 2017 20/27
External IterationThe client takes full control over the iteration process andthe actions that are applied to each item.
Internal IterationThe sequence (produced by the collection) itself determineshow elements in a sequence are accessed and the userdefines the actions applied the items.
Jan Trienes, adapted by Th. Dorssers, Pieter van den Hombergh/FHTenL Lambda Expressions and Java 8 Streams February 24, 2017 21/27
New functionality for Collections frameworkSupport for parallel bulk operationsHeavily uses the stream concept (like in filter())Better separation of “what” or “how” based on lambdaexpressions.
Jan Trienes, adapted by Th. Dorssers, Pieter van den Hombergh/FHTenL Lambda Expressions and Java 8 Streams February 24, 2017 22/27
What is a stream?A stream seems in some way similar to a collection, allowingyou to transform and retrieve data. But there are significantdifferences:
A stream does not store any elements. It is more or lessa n (active) bystander. The elements are ’produced’ byan underlying collection or generated on demand.Stream operations do not mutate their sources. Instead,the source typically returns a new stream for further use.Stream operations are lazy when possible. This meansthey are not executed until their result is needed. Forexample, if you only ask for the first five long wordsinstead of counting them all, then the filter will stopfiltering after the fifth match.
Jan Trienes, adapted by Th. Dorssers, Pieter van den Hombergh/FHTenL Lambda Expressions and Java 8 Streams February 24, 2017 23/27
The previously mentioned operations belong to twocategories:Intermediate operation returns a stream, which can be used
for further processingTerminal operation returns a final result or void, which
can not be used again
Intermediate operations support a programming stylewhich is known as fluent programming. It’s the chainingof operations.The typical chain contains the operations filter(intermediate), map (intermediate), andreduce(terminal).
Reduce as in reduction: indikken, inkoken, einkochen.reduce examples: count, take average, collect into list.
Jan Trienes, adapted by Th. Dorssers, Pieter van den Hombergh/FHTenL Lambda Expressions and Java 8 Streams February 24, 2017 25/27