lambda expressions and java 8 streams · java 8 streams jan trienes, adapted by th. dorssers,...

27
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

Upload: others

Post on 06-Aug-2020

26 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 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

LambdaExpressions andJava 8 Streams

Jan Trienes,adapted by Th.Dorssers, Pieter

van den Hombergh

Contents of thistalk.

IntroductionDefinition

Why Lambdas

Syntax

Short Forms

Ad-hocFunctionalityFunctionality as argument

Representation ofLambda ExpressionFunctional Interfaces

Type Inference

Variable Bindingand ScopingVariable Binding

Scoping

Internal/External Iteration

StreamsStreams?

Operations on Streams

Example

AdditionalInformation

Lambda Expressions and Java 8 Streams

Jan Trienes, adapted by Th. Dorssers, Pieter van denHombergh

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

Page 2: 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

LambdaExpressions andJava 8 Streams

Jan Trienes,adapted by Th.Dorssers, Pieter

van den Hombergh

Contents of thistalk.

IntroductionDefinition

Why Lambdas

Syntax

Short Forms

Ad-hocFunctionalityFunctionality as argument

Representation ofLambda ExpressionFunctional Interfaces

Type Inference

Variable Bindingand ScopingVariable Binding

Scoping

Internal/External Iteration

StreamsStreams?

Operations on Streams

Example

AdditionalInformation

Contents of this talk

IntroductionDefinitionWhy LambdasSyntaxShort Forms

Ad-hoc FunctionalityFunctionality as argument

Representation of LambdaExpression

Functional InterfacesType Inference

Variable Binding and ScopingInternal/ExternalIteration

StreamsStreams?Operations on Streams

Jan Trienes, adapted by Th. Dorssers, Pieter van den Hombergh/FHTenL Lambda Expressions and Java 8 Streams February 24, 2017 2/27

Page 3: 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

LambdaExpressions andJava 8 Streams

Jan Trienes,adapted by Th.Dorssers, Pieter

van den Hombergh

Contents of thistalk.

IntroductionDefinition

Why Lambdas

Syntax

Short Forms

Ad-hocFunctionalityFunctionality as argument

Representation ofLambda ExpressionFunctional Interfaces

Type Inference

Variable Bindingand ScopingVariable Binding

Scoping

Internal/External Iteration

StreamsStreams?

Operations on Streams

Example

AdditionalInformation

Lambda Expression

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

Page 4: 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

LambdaExpressions andJava 8 Streams

Jan Trienes,adapted by Th.Dorssers, Pieter

van den Hombergh

Contents of thistalk.

IntroductionDefinition

Why Lambdas

Syntax

Short Forms

Ad-hocFunctionalityFunctionality as argument

Representation ofLambda ExpressionFunctional Interfaces

Type Inference

Variable Bindingand ScopingVariable Binding

Scoping

Internal/External Iteration

StreamsStreams?

Operations on Streams

Example

AdditionalInformation

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

Page 5: 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

LambdaExpressions andJava 8 Streams

Jan Trienes,adapted by Th.Dorssers, Pieter

van den Hombergh

Contents of thistalk.

IntroductionDefinition

Why Lambdas

Syntax

Short Forms

Ad-hocFunctionalityFunctionality as argument

Representation ofLambda ExpressionFunctional Interfaces

Type Inference

Variable Bindingand ScopingVariable Binding

Scoping

Internal/External Iteration

StreamsStreams?

Operations on Streams

Example

AdditionalInformation

SyntaxProperties of a lambda:

3 Parameter List3 Function Body3 Return Type3 Exceptions7 Name

Lambda Syntax Java( 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 5/27

Page 6: 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

LambdaExpressions andJava 8 Streams

Jan Trienes,adapted by Th.Dorssers, Pieter

van den Hombergh

Contents of thistalk.

IntroductionDefinition

Why Lambdas

Syntax

Short Forms

Ad-hocFunctionalityFunctionality as argument

Representation ofLambda ExpressionFunctional Interfaces

Type Inference

Variable Bindingand ScopingVariable Binding

Scoping

Internal/External Iteration

StreamsStreams?

Operations on Streams

Example

AdditionalInformation

Syntax Explanation

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

Page 7: 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

LambdaExpressions andJava 8 Streams

Jan Trienes,adapted by Th.Dorssers, Pieter

van den Hombergh

Contents of thistalk.

IntroductionDefinition

Why Lambdas

Syntax

Short Forms

Ad-hocFunctionalityFunctionality as argument

Representation ofLambda ExpressionFunctional Interfaces

Type Inference

Variable Bindingand ScopingVariable Binding

Scoping

Internal/External Iteration

StreamsStreams?

Operations on Streams

Example

AdditionalInformation

Example 1The definition of a lambda expression via a functionalinterface.

@FunctionalInterfacei n t e r f a c e Calculator {

/*** Compute a value from the inputs .** @param a first input* @param b second input* @return result of the computation*/

i n t calculate ( i n t a , i n t b ) ;}

Who is SAM again?

Jan Trienes, adapted by Th. Dorssers, Pieter van den Hombergh/FHTenL Lambda Expressions and Java 8 Streams February 24, 2017 7/27

Page 8: 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

LambdaExpressions andJava 8 Streams

Jan Trienes,adapted by Th.Dorssers, Pieter

van den Hombergh

Contents of thistalk.

IntroductionDefinition

Why Lambdas

Syntax

Short Forms

Ad-hocFunctionalityFunctionality as argument

Representation ofLambda ExpressionFunctional Interfaces

Type Inference

Variable Bindingand ScopingVariable Binding

Scoping

Internal/External Iteration

StreamsStreams?

Operations on Streams

Example

AdditionalInformation

Example 1, continued

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

Page 9: 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

LambdaExpressions andJava 8 Streams

Jan Trienes,adapted by Th.Dorssers, Pieter

van den Hombergh

Contents of thistalk.

IntroductionDefinition

Why Lambdas

Syntax

Short Forms

Ad-hocFunctionalityFunctionality as argument

Representation ofLambda ExpressionFunctional Interfaces

Type Inference

Variable Bindingand ScopingVariable Binding

Scoping

Internal/External Iteration

StreamsStreams?

Operations on Streams

Example

AdditionalInformation

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

Page 10: 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

LambdaExpressions andJava 8 Streams

Jan Trienes,adapted by Th.Dorssers, Pieter

van den Hombergh

Contents of thistalk.

IntroductionDefinition

Why Lambdas

Syntax

Short Forms

Ad-hocFunctionalityFunctionality as argument

Representation ofLambda ExpressionFunctional Interfaces

Type Inference

Variable Bindingand ScopingVariable Binding

Scoping

Internal/External Iteration

StreamsStreams?

Operations on Streams

Example

AdditionalInformation

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 )←↩

method .9 filter ( personList , Person : : isFullAged ) ;

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

Page 11: 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

LambdaExpressions andJava 8 Streams

Jan Trienes,adapted by Th.Dorssers, Pieter

van den Hombergh

Contents of thistalk.

IntroductionDefinition

Why Lambdas

Syntax

Short Forms

Ad-hocFunctionalityFunctionality as argument

Representation ofLambda ExpressionFunctional Interfaces

Type Inference

Variable Bindingand ScopingVariable Binding

Scoping

Internal/External Iteration

StreamsStreams?

Operations on Streams

Example

AdditionalInformation

Ad-hoc Functionality

Ad hoc implementationLambda expressions are implemented “ad hoc”, right whenand where they are needed. This is similar to anonymousinner-classes.

Code as dataBoth lambda expressions and anonymous inner-classes arepassed as arguments to a function which applies them. Thisis known as code as data.

Are related to:delegates in Swift, objective-C (Apple) and C# (dotNet)call back functions in C/C++

Jan Trienes, adapted by Th. Dorssers, Pieter van den Hombergh/FHTenL Lambda Expressions and Java 8 Streams February 24, 2017 11/27

Page 12: 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

LambdaExpressions andJava 8 Streams

Jan Trienes,adapted by Th.Dorssers, Pieter

van den Hombergh

Contents of thistalk.

IntroductionDefinition

Why Lambdas

Syntax

Short Forms

Ad-hocFunctionalityFunctionality as argument

Representation ofLambda ExpressionFunctional Interfaces

Type Inference

Variable Bindingand ScopingVariable Binding

Scoping

Internal/External Iteration

StreamsStreams?

Operations on Streams

Example

AdditionalInformation

Lambda vs. Anonymous inner-classWithout lambdas:

Anonymous inner-classfilter ( personList , new PersonFilter ( ) {

@Overridep u b l i c b o o l e a n accept ( Person p ) {

r e t u r n p . isFullAged ( ) ;}

}) ;

Same with lambdas:

Lambda expressionfilter ( personList , p −> p . isFullAged ( ) ) ;

Jan Trienes, adapted by Th. Dorssers, Pieter van den Hombergh/FHTenL Lambda Expressions and Java 8 Streams February 24, 2017 12/27

Page 13: 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

LambdaExpressions andJava 8 Streams

Jan Trienes,adapted by Th.Dorssers, Pieter

van den Hombergh

Contents of thistalk.

IntroductionDefinition

Why Lambdas

Syntax

Short Forms

Ad-hocFunctionalityFunctionality as argument

Representation ofLambda ExpressionFunctional Interfaces

Type Inference

Variable Bindingand ScopingVariable Binding

Scoping

Internal/External Iteration

StreamsStreams?

Operations on Streams

Example

AdditionalInformation

Lambda vs. Anonymous inner-class

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

Page 14: 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

LambdaExpressions andJava 8 Streams

Jan Trienes,adapted by Th.Dorssers, Pieter

van den Hombergh

Contents of thistalk.

IntroductionDefinition

Why Lambdas

Syntax

Short Forms

Ad-hocFunctionalityFunctionality as argument

Representation ofLambda ExpressionFunctional Interfaces

Type Inference

Variable Bindingand ScopingVariable Binding

Scoping

Internal/External Iteration

StreamsStreams?

Operations on Streams

Example

AdditionalInformation

Representation of Lambda Expressions

Function → ObjectWhen a lambda expression is used, we define a function.The receiving part uses it as an object.

c is the receiving object

p u b l i c ReCalc ( ){}

p u b l i c i n t calculate ( Calculator c , i n t n ) {r e t u r n c . calculate ( n ) ;

}

Internal representationAs everything else in Java, a lambda expression is a regularobject, which has an address and a type.

Jan Trienes, adapted by Th. Dorssers, Pieter van den Hombergh/FHTenL Lambda Expressions and Java 8 Streams February 24, 2017 14/27

Page 15: 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

LambdaExpressions andJava 8 Streams

Jan Trienes,adapted by Th.Dorssers, Pieter

van den Hombergh

Contents of thistalk.

IntroductionDefinition

Why Lambdas

Syntax

Short Forms

Ad-hocFunctionalityFunctionality as argument

Representation ofLambda ExpressionFunctional Interfaces

Type Inference

Variable Bindingand ScopingVariable Binding

Scoping

Internal/External Iteration

StreamsStreams?

Operations on Streams

Example

AdditionalInformation

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

Page 16: 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

LambdaExpressions andJava 8 Streams

Jan Trienes,adapted by Th.Dorssers, Pieter

van den Hombergh

Contents of thistalk.

IntroductionDefinition

Why Lambdas

Syntax

Short Forms

Ad-hocFunctionalityFunctionality as argument

Representation ofLambda ExpressionFunctional Interfaces

Type Inference

Variable Bindingand ScopingVariable Binding

Scoping

Internal/External Iteration

StreamsStreams?

Operations on Streams

Example

AdditionalInformation

Type Inference

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

Page 17: 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

LambdaExpressions andJava 8 Streams

Jan Trienes,adapted by Th.Dorssers, Pieter

van den Hombergh

Contents of thistalk.

IntroductionDefinition

Why Lambdas

Syntax

Short Forms

Ad-hocFunctionalityFunctionality as argument

Representation ofLambda ExpressionFunctional Interfaces

Type Inference

Variable Bindingand ScopingVariable Binding

Scoping

Internal/External Iteration

StreamsStreams?

Operations on Streams

Example

AdditionalInformation

Variable Binding and Scoping

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

Page 18: 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

LambdaExpressions andJava 8 Streams

Jan Trienes,adapted by Th.Dorssers, Pieter

van den Hombergh

Contents of thistalk.

IntroductionDefinition

Why Lambdas

Syntax

Short Forms

Ad-hocFunctionalityFunctionality as argument

Representation ofLambda ExpressionFunctional Interfaces

Type Inference

Variable Bindingand ScopingVariable Binding

Scoping

Internal/External Iteration

StreamsStreams?

Operations on Streams

Example

AdditionalInformation

Variable BindingConsider the following example:

Variable Bindingv o i d method ( ) {

Work work = new Work ( ) ;

Thread t = new Thread ( ( ) −> {work . process ( ) ;

}) ;}

The lambda expression needs access to a variabledefined in the enclosing context.This variable is now bound to that expression.(implicitly final)

Jan Trienes, adapted by Th. Dorssers, Pieter van den Hombergh/FHTenL Lambda Expressions and Java 8 Streams February 24, 2017 18/27

Page 19: 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

LambdaExpressions andJava 8 Streams

Jan Trienes,adapted by Th.Dorssers, Pieter

van den Hombergh

Contents of thistalk.

IntroductionDefinition

Why Lambdas

Syntax

Short Forms

Ad-hocFunctionalityFunctionality as argument

Representation ofLambda ExpressionFunctional Interfaces

Type Inference

Variable Bindingand ScopingVariable Binding

Scoping

Internal/External Iteration

StreamsStreams?

Operations on Streams

Example

AdditionalInformation

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

Page 20: 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

LambdaExpressions andJava 8 Streams

Jan Trienes,adapted by Th.Dorssers, Pieter

van den Hombergh

Contents of thistalk.

IntroductionDefinition

Why Lambdas

Syntax

Short Forms

Ad-hocFunctionalityFunctionality as argument

Representation ofLambda ExpressionFunctional Interfaces

Type Inference

Variable Bindingand ScopingVariable Binding

Scoping

Internal/External Iteration

StreamsStreams?

Operations on Streams

Example

AdditionalInformation

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

Page 21: 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

LambdaExpressions andJava 8 Streams

Jan Trienes,adapted by Th.Dorssers, Pieter

van den Hombergh

Contents of thistalk.

IntroductionDefinition

Why Lambdas

Syntax

Short Forms

Ad-hocFunctionalityFunctionality as argument

Representation ofLambda ExpressionFunctional Interfaces

Type Inference

Variable Bindingand ScopingVariable Binding

Scoping

Internal/External Iteration

StreamsStreams?

Operations on Streams

Example

AdditionalInformation

Internal vs. External Iteration

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

Page 22: 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

LambdaExpressions andJava 8 Streams

Jan Trienes,adapted by Th.Dorssers, Pieter

van den Hombergh

Contents of thistalk.

IntroductionDefinition

Why Lambdas

Syntax

Short Forms

Ad-hocFunctionalityFunctionality as argument

Representation ofLambda ExpressionFunctional Interfaces

Type Inference

Variable Bindingand ScopingVariable Binding

Scoping

Internal/External Iteration

StreamsStreams?

Operations on Streams

Example

AdditionalInformation

Streams API

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

Page 23: 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

LambdaExpressions andJava 8 Streams

Jan Trienes,adapted by Th.Dorssers, Pieter

van den Hombergh

Contents of thistalk.

IntroductionDefinition

Why Lambdas

Syntax

Short Forms

Ad-hocFunctionalityFunctionality as argument

Representation ofLambda ExpressionFunctional Interfaces

Type Inference

Variable Bindingand ScopingVariable Binding

Scoping

Internal/External Iteration

StreamsStreams?

Operations on Streams

Example

AdditionalInformation

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

Page 24: 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

LambdaExpressions andJava 8 Streams

Jan Trienes,adapted by Th.Dorssers, Pieter

van den Hombergh

Contents of thistalk.

IntroductionDefinition

Why Lambdas

Syntax

Short Forms

Ad-hocFunctionalityFunctionality as argument

Representation ofLambda ExpressionFunctional Interfaces

Type Inference

Variable Bindingand ScopingVariable Binding

Scoping

Internal/External Iteration

StreamsStreams?

Operations on Streams

Example

AdditionalInformation

Operations on StreamsSome of the new operations

filter() select. only those items, that match apredicate are contained. in the result. I

map() transform creates a new stream out of theresults from the passed function. I

distinct() deduplicate returns a stream in which all itemsare distinct. Implies sorting of sorts. I

count() reduce returns the number of items in thestream. T

forEach() sic. applies a passed function to each item inthe stream. T.

Jan Trienes, adapted by Th. Dorssers, Pieter van den Hombergh/FHTenL Lambda Expressions and Java 8 Streams February 24, 2017 24/27

Page 25: 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

LambdaExpressions andJava 8 Streams

Jan Trienes,adapted by Th.Dorssers, Pieter

van den Hombergh

Contents of thistalk.

IntroductionDefinition

Why Lambdas

Syntax

Short Forms

Ad-hocFunctionalityFunctionality as argument

Representation ofLambda ExpressionFunctional Interfaces

Type Inference

Variable Bindingand ScopingVariable Binding

Scoping

Internal/External Iteration

StreamsStreams?

Operations on Streams

Example

AdditionalInformation

Terminal and Intermediate Operations

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

Page 26: 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

LambdaExpressions andJava 8 Streams

Jan Trienes,adapted by Th.Dorssers, Pieter

van den Hombergh

Contents of thistalk.

IntroductionDefinition

Why Lambdas

Syntax

Short Forms

Ad-hocFunctionalityFunctionality as argument

Representation ofLambda ExpressionFunctional Interfaces

Type Inference

Variable Bindingand ScopingVariable Binding

Scoping

Internal/External Iteration

StreamsStreams?

Operations on Streams

Example

AdditionalInformation

An Example using StreamsGoal: Find the names of all persons which are no olderthan 30 and which name ends with “daal”.

Example of applying streams

v o i d method ( ) {List<Person> personList = new ArrayList<>() ;personList . add ( new Person ( "John Doe" , 15) ) ;personList . add ( new Person ( "Jane Doe" , 17) ) ;personList . add ( new Person ( "Anne Modaal " , 35) ) ;personList . add ( new Person ( "Max Modaal " , 19) ) ;personList . add ( new Person ( " Erika Modaal " , 28) ) ;

personList. parallelStream ( ) // supports parallel execution. filter ( p −> p . age <= 30). map ( p : : getName ). filter ( s −> s . toLowerCase ( ) . endsWith ( "daal" ) ). forEach ( ( String s ) −> System . out . println ( s ) ) ;

}

Exercise See example above.Find the stream implementation of the following: calculatethe average age of these persons.

Jan Trienes, adapted by Th. Dorssers, Pieter van den Hombergh/FHTenL Lambda Expressions and Java 8 Streams February 24, 2017 26/27

Page 27: 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

LambdaExpressions andJava 8 Streams

Jan Trienes,adapted by Th.Dorssers, Pieter

van den Hombergh

Contents of thistalk.

IntroductionDefinition

Why Lambdas

Syntax

Short Forms

Ad-hocFunctionalityFunctionality as argument

Representation ofLambda ExpressionFunctional Interfaces

Type Inference

Variable Bindingand ScopingVariable Binding

Scoping

Internal/External Iteration

StreamsStreams?

Operations on Streams

Example

AdditionalInformation

Additional Information

Tutorial on Java 8 and lambda expressions by AngelikaLanger and Klaus Kreft http://angelikalanger.com/Lambdas/Lambdas.html

java.util.stream

java.util.function

Jan Trienes, adapted by Th. Dorssers, Pieter van den Hombergh/FHTenL Lambda Expressions and Java 8 Streams February 24, 2017 27/27