SlideShare a Scribd company logo
1 of 28
Lambdas & Streams Laboratory
Simon Ritter
Oracle Corp.
Twitter: @speakjava
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Lambdas and Functions
Library Review
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Lambda Expressions
• Lambda expression is an anonymous function
• Think of it like a method
– But not associated with a class
• Can be used wherever you would use an anonymous inner class
– Single abstract method type
• Syntax
– ( [optional-parameters] ) -> body
• Types can be inferred (parameters and return type)
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Lambda Examples
SomeList<Student> students = ...
double highestScore =
students.stream().
filter(Student s -> s.getGradYear() == 2011).
map(Student s -> s.getScore()).
max();
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Method References
• Method references let us reuse a method as a lambda expression
FileFilter x = (File f) -> f.canRead();
FileFilter x = File::canRead;
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
The Stream Class
• Stream<T>
– A sequence of elements supporting sequential and parallel operations
• A Stream is opened by calling:
– Collection.stream()
– Collection.parallelStream()
• Many Stream methods return Stream objects
– Very simple (and logical) method chaining
java.util.stream
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Stream Basics
• Using a Stream means having three things
• A source
– Something that creates a Stream of objects
• Zero or more intermediate objects
– Take a Stream as input, produce a Stream as output
– Potentially create a new Stream (but don’t have to)
• A terminal operation
– Takes a Stream as input
– Consumes the Stream, or generates some other type of output
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Map Values in a Stream
Maps and FlatMaps
Map
FlatMap
Input Stream
Input Stream
1 to 1 mapping
1 to many mapping
Output Stream
Output Stream
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Stream Usage
• Multiple operations available
– collect, filter, count, skip, limit, sorted
– map (and map to types, e.g. mapToInt)
– flatMap maps each element in a Stream to possibly multiple elements
• e.g. flatMap(line -> Stream.of(line.split(REGEXP));
List<String> names = Arrays.asList(“Bob”, “Alice”, “Charlie”);
System.out.println(names.
stream().
filter(e -> e.getLength() > 4).
findFirst().
get());
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
java.util.function 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 function to the input type T, generating a result of type R
• Supplier<T>
– A supplier of results of type T
• Plus several more type specific versions
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
The iterable Interface
• One method
– forEach()
– The parameter is a Consumer
Used by most collections
wordList.forEach(s -> System.out.println(s));
wordList.forEach(System.out::println);
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Files and Lines of Text
• BufferedReader has new method
– Stream<String> lines()
• HINT: Test framework creates a BufferedReader for you
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Useful Stream Methods
• collect (terminal)
• filter (intermediate)
• count (terminal)
• skip, limit (intermediate)
• max (terminal)
• getAsInt (terminal)
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Getting Started
• Open the LambdasHOL project in your IDE
• The exercises are configured as tests
• Edit each test’s method
– Remove the @Ignore annotation
• Run the tests
– Right-click the Exercises.java file and select Run as > JUnit Test
• Make the tests pass
• Simple!
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Access To The Files
1. USB keys at front
2. www.github.com/speakjava/Lambda_Lab-EclipseCon
3. www.github.com/speakjava/Lambda_Lab-NetBeans
16
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Let’s Go!
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Solutions
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 19
First character of each word concatenated
Exercise 1
StringBuilder sb = new StringBuilder();
input.forEach(s -> s.append(s.charAt(0)));
String result = sb.toString();
String result = input.stream()
.map(s -> s.substring(0, 1))
.reduce("", (a, b) -> a + b);
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 20
Map whose keys are first letter, values are sum of lengths
Exercise 5
Map<String, Integer> result = new TreeMap();
list.forEach(s ->
result.merge(s.substring(0, 1),
s.length(),
Integer::sum));
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 21
Find the length of the longest line
Exercise 9
int longest = reader.lines()
.mapToInt(String::length)
.max()
.getAsInt();
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 22
Find the longest line
Exercise 10
String longest = reader.lines()
.max(comparingInt(String::length))
.get();
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 23
Select the set of words whose length is greater than the word's position
Exercise 11
List<String> result = IntStream.range(0, input.size())
.filter(pos -> input.get(pos).length() > pos)
.mpToObj(pos -> input.get(pos))
.collect(toList());
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 24
Convert a list of strings into a list of characters
Exercise 13
List<Character> result = input.stream()
.flatMap(word -> word.chars().mapToObj(i -> (char)i))
.map(c -> (Character)c)
,collect(toList());
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 25
Sort unique, lower-cased words by length, then alphabetically within length
Exercise 17
List<String> result = reader.lines()
.flatMap(line -> Stream.of(line.split(REGEXP)))
.map(String::toLowerCase)
.distinct()
.sorted(comparingInt(String::length)
.thenComparing(naturalOrder()))
.collect(toList());
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 26
Count total number of words and distinct lower-cased words in one pass
Exercise 18
LongAdder adder = new LongAdder();
long distinctCount = reader.lines()
.flatMap(line -> Stream.of(line.split(REGEXP)))
.map(String::toLowerCase)
.peek(s -> adder.increment())
.distinct()
.count();
Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 27
Compute the value of 21! (which needs to use BigInteger)
Exercise 19
BigInteger result = IntStream.rangeClosed(1, 21)
.mapToObj(n -> BigInteger.valueOf(n))
.reduce(BigInteger.ONE, (m, n) -> m.multiply(n));
T merge(T identity, BiFunction accumulator) ===
T result = identity;
for (T element : this stream)
result = accumulator.apply(result, element)
return result;
Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
Graphic Section Divider

More Related Content

What's hot

It's Java Jim, But Not As We Know It!
It's Java Jim, But Not As We Know It!It's Java Jim, But Not As We Know It!
It's Java Jim, But Not As We Know It!Simon Ritter
 
Functional programming with_jdk8-s_ritter
Functional programming with_jdk8-s_ritterFunctional programming with_jdk8-s_ritter
Functional programming with_jdk8-s_ritterSimon Ritter
 
It's Java, Jim, but not as we know it
It's Java, Jim, but not as we know itIt's Java, Jim, but not as we know it
It's Java, Jim, but not as we know itSimon Ritter
 
Whats New For Developers In JDK 9
Whats New For Developers In JDK 9Whats New For Developers In JDK 9
Whats New For Developers In JDK 9Simon Ritter
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8Martin Toshev
 
Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Ganesh Samarthyam
 
How Green are Java Best Coding Practices? - GreenDays @ Rennes - 2014-07-01
How Green are Java Best Coding Practices? - GreenDays @ Rennes - 2014-07-01How Green are Java Best Coding Practices? - GreenDays @ Rennes - 2014-07-01
How Green are Java Best Coding Practices? - GreenDays @ Rennes - 2014-07-01Jérôme Rocheteau
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 itiAhmed mar3y
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8Knoldus Inc.
 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Ganesh Samarthyam
 
JDK 14 Lots of New Features
JDK 14 Lots of New FeaturesJDK 14 Lots of New Features
JDK 14 Lots of New FeaturesSimon Ritter
 
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time APIModern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time APIGanesh Samarthyam
 

What's hot (20)

It's Java Jim, But Not As We Know It!
It's Java Jim, But Not As We Know It!It's Java Jim, But Not As We Know It!
It's Java Jim, But Not As We Know It!
 
Functional programming with_jdk8-s_ritter
Functional programming with_jdk8-s_ritterFunctional programming with_jdk8-s_ritter
Functional programming with_jdk8-s_ritter
 
Apouc 2014-java-8-create-the-future
Apouc 2014-java-8-create-the-futureApouc 2014-java-8-create-the-future
Apouc 2014-java-8-create-the-future
 
It's Java, Jim, but not as we know it
It's Java, Jim, but not as we know itIt's Java, Jim, but not as we know it
It's Java, Jim, but not as we know it
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
 
Whats New For Developers In JDK 9
Whats New For Developers In JDK 9Whats New For Developers In JDK 9
Whats New For Developers In JDK 9
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
JDK8 Streams
JDK8 StreamsJDK8 Streams
JDK8 Streams
 
Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8
 
Streams in Java 8
Streams in Java 8Streams in Java 8
Streams in Java 8
 
Java 8 Feature Preview
Java 8 Feature PreviewJava 8 Feature Preview
Java 8 Feature Preview
 
Java 8 streams
Java 8 streamsJava 8 streams
Java 8 streams
 
How Green are Java Best Coding Practices? - GreenDays @ Rennes - 2014-07-01
How Green are Java Best Coding Practices? - GreenDays @ Rennes - 2014-07-01How Green are Java Best Coding Practices? - GreenDays @ Rennes - 2014-07-01
How Green are Java Best Coding Practices? - GreenDays @ Rennes - 2014-07-01
 
New features in jdk8 iti
New features in jdk8 itiNew features in jdk8 iti
New features in jdk8 iti
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
 
Java8 features
Java8 featuresJava8 features
Java8 features
 
Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams Productive Programming in Java 8 - with Lambdas and Streams
Productive Programming in Java 8 - with Lambdas and Streams
 
JDK 14 Lots of New Features
JDK 14 Lots of New FeaturesJDK 14 Lots of New Features
JDK 14 Lots of New Features
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time APIModern Programming in Java 8 - Lambdas, Streams and Date Time API
Modern Programming in Java 8 - Lambdas, Streams and Date Time API
 

Similar to Lambdas Hands On Lab

Functional Programming With Lambdas and Streams in JDK8
 Functional Programming With Lambdas and Streams in JDK8 Functional Programming With Lambdas and Streams in JDK8
Functional Programming With Lambdas and Streams in JDK8IndicThreads
 
Improved Developer Productivity In JDK8
Improved Developer Productivity In JDK8Improved Developer Productivity In JDK8
Improved Developer Productivity In JDK8Simon Ritter
 
What's New in Java 8
What's New in Java 8What's New in Java 8
What's New in Java 8javafxpert
 
Lambdas And Streams in JDK8
Lambdas And Streams in JDK8Lambdas And Streams in JDK8
Lambdas And Streams in JDK8Simon Ritter
 
Lambdas & Streams
Lambdas & StreamsLambdas & Streams
Lambdas & StreamsC4Media
 
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...jaxLondonConference
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streamsjessitron
 
The Road to Lambda - Mike Duigou
The Road to Lambda - Mike DuigouThe Road to Lambda - Mike Duigou
The Road to Lambda - Mike Duigoujaxconf
 
Cascading - A Java Developer’s Companion to the Hadoop World
Cascading - A Java Developer’s Companion to the Hadoop WorldCascading - A Java Developer’s Companion to the Hadoop World
Cascading - A Java Developer’s Companion to the Hadoop WorldCascading
 
A brief tour of modern Java
A brief tour of modern JavaA brief tour of modern Java
A brief tour of modern JavaSina Madani
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard LibrarySantosh Rajan
 
Java 8 New features
Java 8 New featuresJava 8 New features
Java 8 New featuresSon Nguyen
 
Java 8 - Lambdas and much more
Java 8 - Lambdas and much moreJava 8 - Lambdas and much more
Java 8 - Lambdas and much moreAlin Pandichi
 
Oracle REST Data Services: Options for your Web Services
Oracle REST Data Services: Options for your Web ServicesOracle REST Data Services: Options for your Web Services
Oracle REST Data Services: Options for your Web ServicesJeff Smith
 
A Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIA Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIJörn Guy Süß JGS
 

Similar to Lambdas Hands On Lab (20)

Functional Programming With Lambdas and Streams in JDK8
 Functional Programming With Lambdas and Streams in JDK8 Functional Programming With Lambdas and Streams in JDK8
Functional Programming With Lambdas and Streams in JDK8
 
Improved Developer Productivity In JDK8
Improved Developer Productivity In JDK8Improved Developer Productivity In JDK8
Improved Developer Productivity In JDK8
 
What's New in Java 8
What's New in Java 8What's New in Java 8
What's New in Java 8
 
Lambdas And Streams in JDK8
Lambdas And Streams in JDK8Lambdas And Streams in JDK8
Lambdas And Streams in JDK8
 
Lambdas & Streams
Lambdas & StreamsLambdas & Streams
Lambdas & Streams
 
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
Project Lambda: Functional Programming Constructs in Java - Simon Ritter (Ora...
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
 
Java 8
Java 8Java 8
Java 8
 
The Road to Lambda - Mike Duigou
The Road to Lambda - Mike DuigouThe Road to Lambda - Mike Duigou
The Road to Lambda - Mike Duigou
 
Cascading - A Java Developer’s Companion to the Hadoop World
Cascading - A Java Developer’s Companion to the Hadoop WorldCascading - A Java Developer’s Companion to the Hadoop World
Cascading - A Java Developer’s Companion to the Hadoop World
 
Java8
Java8Java8
Java8
 
A brief tour of modern Java
A brief tour of modern JavaA brief tour of modern Java
A brief tour of modern Java
 
Lambdas and Laughs
Lambdas and LaughsLambdas and Laughs
Lambdas and Laughs
 
Java 8 new features
Java 8 new featuresJava 8 new features
Java 8 new features
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard Library
 
Java 8 Intro - Core Features
Java 8 Intro - Core FeaturesJava 8 Intro - Core Features
Java 8 Intro - Core Features
 
Java 8 New features
Java 8 New featuresJava 8 New features
Java 8 New features
 
Java 8 - Lambdas and much more
Java 8 - Lambdas and much moreJava 8 - Lambdas and much more
Java 8 - Lambdas and much more
 
Oracle REST Data Services: Options for your Web Services
Oracle REST Data Services: Options for your Web ServicesOracle REST Data Services: Options for your Web Services
Oracle REST Data Services: Options for your Web Services
 
A Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its APIA Brief Conceptual Introduction to Functional Java 8 and its API
A Brief Conceptual Introduction to Functional Java 8 and its API
 

More from Simon Ritter

Cloud Native Compiler
Cloud Native CompilerCloud Native Compiler
Cloud Native CompilerSimon Ritter
 
The Art of Java Type Patterns
The Art of Java Type PatternsThe Art of Java Type Patterns
The Art of Java Type PatternsSimon Ritter
 
Modern Java Workshop
Modern Java WorkshopModern Java Workshop
Modern Java WorkshopSimon Ritter
 
Java performance monitoring
Java performance monitoringJava performance monitoring
Java performance monitoringSimon Ritter
 
Modern Java Workshop
Modern Java WorkshopModern Java Workshop
Modern Java WorkshopSimon Ritter
 
Getting the Most From Modern Java
Getting the Most From Modern JavaGetting the Most From Modern Java
Getting the Most From Modern JavaSimon Ritter
 
Building a Better JVM
Building a Better JVMBuilding a Better JVM
Building a Better JVMSimon Ritter
 
How to Choose a JDK
How to Choose a JDKHow to Choose a JDK
How to Choose a JDKSimon Ritter
 
The Latest in Enterprise JavaBeans Technology
The Latest in Enterprise JavaBeans TechnologyThe Latest in Enterprise JavaBeans Technology
The Latest in Enterprise JavaBeans TechnologySimon Ritter
 
Developing Enterprise Applications Using Java Technology
Developing Enterprise Applications Using Java TechnologyDeveloping Enterprise Applications Using Java Technology
Developing Enterprise Applications Using Java TechnologySimon Ritter
 
Is Java Still Free?
Is Java Still Free?Is Java Still Free?
Is Java Still Free?Simon Ritter
 
Moving Towards JDK 12
Moving Towards JDK 12Moving Towards JDK 12
Moving Towards JDK 12Simon Ritter
 
JDK 9, 10, 11 and Beyond
JDK 9, 10, 11 and BeyondJDK 9, 10, 11 and Beyond
JDK 9, 10, 11 and BeyondSimon Ritter
 
Java Is Still Free
Java Is Still FreeJava Is Still Free
Java Is Still FreeSimon Ritter
 
JDK 9, 10, 11 and Beyond
JDK 9, 10, 11 and BeyondJDK 9, 10, 11 and Beyond
JDK 9, 10, 11 and BeyondSimon Ritter
 
JDK 9 and JDK 10 Deep Dive
JDK 9 and JDK 10 Deep DiveJDK 9 and JDK 10 Deep Dive
JDK 9 and JDK 10 Deep DiveSimon Ritter
 

More from Simon Ritter (20)

Cloud Native Compiler
Cloud Native CompilerCloud Native Compiler
Cloud Native Compiler
 
Java On CRaC
Java On CRaCJava On CRaC
Java On CRaC
 
The Art of Java Type Patterns
The Art of Java Type PatternsThe Art of Java Type Patterns
The Art of Java Type Patterns
 
Modern Java Workshop
Modern Java WorkshopModern Java Workshop
Modern Java Workshop
 
Java performance monitoring
Java performance monitoringJava performance monitoring
Java performance monitoring
 
Modern Java Workshop
Modern Java WorkshopModern Java Workshop
Modern Java Workshop
 
Getting the Most From Modern Java
Getting the Most From Modern JavaGetting the Most From Modern Java
Getting the Most From Modern Java
 
Building a Better JVM
Building a Better JVMBuilding a Better JVM
Building a Better JVM
 
Java after 8
Java after 8Java after 8
Java after 8
 
How to Choose a JDK
How to Choose a JDKHow to Choose a JDK
How to Choose a JDK
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 
The Latest in Enterprise JavaBeans Technology
The Latest in Enterprise JavaBeans TechnologyThe Latest in Enterprise JavaBeans Technology
The Latest in Enterprise JavaBeans Technology
 
Developing Enterprise Applications Using Java Technology
Developing Enterprise Applications Using Java TechnologyDeveloping Enterprise Applications Using Java Technology
Developing Enterprise Applications Using Java Technology
 
Is Java Still Free?
Is Java Still Free?Is Java Still Free?
Is Java Still Free?
 
Moving Towards JDK 12
Moving Towards JDK 12Moving Towards JDK 12
Moving Towards JDK 12
 
JDK 9, 10, 11 and Beyond
JDK 9, 10, 11 and BeyondJDK 9, 10, 11 and Beyond
JDK 9, 10, 11 and Beyond
 
Java Is Still Free
Java Is Still FreeJava Is Still Free
Java Is Still Free
 
JDK 9, 10, 11 and Beyond
JDK 9, 10, 11 and BeyondJDK 9, 10, 11 and Beyond
JDK 9, 10, 11 and Beyond
 
JDK 9 and JDK 10 Deep Dive
JDK 9 and JDK 10 Deep DiveJDK 9 and JDK 10 Deep Dive
JDK 9 and JDK 10 Deep Dive
 
JDK 9 Deep Dive
JDK 9 Deep DiveJDK 9 Deep Dive
JDK 9 Deep Dive
 

Recently uploaded

Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfYashikaSharma391629
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 

Recently uploaded (20)

Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 

Lambdas Hands On Lab

  • 1.
  • 2. Lambdas & Streams Laboratory Simon Ritter Oracle Corp. Twitter: @speakjava Copyright © 2014, Oracle and/or its affiliates. All rights reserved.
  • 3. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Lambdas and Functions Library Review
  • 4. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Lambda Expressions • Lambda expression is an anonymous function • Think of it like a method – But not associated with a class • Can be used wherever you would use an anonymous inner class – Single abstract method type • Syntax – ( [optional-parameters] ) -> body • Types can be inferred (parameters and return type)
  • 5. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Lambda Examples SomeList<Student> students = ... double highestScore = students.stream(). filter(Student s -> s.getGradYear() == 2011). map(Student s -> s.getScore()). max();
  • 6. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Method References • Method references let us reuse a method as a lambda expression FileFilter x = (File f) -> f.canRead(); FileFilter x = File::canRead;
  • 7. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. The Stream Class • Stream<T> – A sequence of elements supporting sequential and parallel operations • A Stream is opened by calling: – Collection.stream() – Collection.parallelStream() • Many Stream methods return Stream objects – Very simple (and logical) method chaining java.util.stream
  • 8. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Stream Basics • Using a Stream means having three things • A source – Something that creates a Stream of objects • Zero or more intermediate objects – Take a Stream as input, produce a Stream as output – Potentially create a new Stream (but don’t have to) • A terminal operation – Takes a Stream as input – Consumes the Stream, or generates some other type of output
  • 9. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Map Values in a Stream Maps and FlatMaps Map FlatMap Input Stream Input Stream 1 to 1 mapping 1 to many mapping Output Stream Output Stream
  • 10. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Stream Usage • Multiple operations available – collect, filter, count, skip, limit, sorted – map (and map to types, e.g. mapToInt) – flatMap maps each element in a Stream to possibly multiple elements • e.g. flatMap(line -> Stream.of(line.split(REGEXP)); List<String> names = Arrays.asList(“Bob”, “Alice”, “Charlie”); System.out.println(names. stream(). filter(e -> e.getLength() > 4). findFirst(). get());
  • 11. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. java.util.function 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 function to the input type T, generating a result of type R • Supplier<T> – A supplier of results of type T • Plus several more type specific versions
  • 12. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. The iterable Interface • One method – forEach() – The parameter is a Consumer Used by most collections wordList.forEach(s -> System.out.println(s)); wordList.forEach(System.out::println);
  • 13. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Files and Lines of Text • BufferedReader has new method – Stream<String> lines() • HINT: Test framework creates a BufferedReader for you
  • 14. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Useful Stream Methods • collect (terminal) • filter (intermediate) • count (terminal) • skip, limit (intermediate) • max (terminal) • getAsInt (terminal)
  • 15. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Getting Started • Open the LambdasHOL project in your IDE • The exercises are configured as tests • Edit each test’s method – Remove the @Ignore annotation • Run the tests – Right-click the Exercises.java file and select Run as > JUnit Test • Make the tests pass • Simple!
  • 16. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Access To The Files 1. USB keys at front 2. www.github.com/speakjava/Lambda_Lab-EclipseCon 3. www.github.com/speakjava/Lambda_Lab-NetBeans 16
  • 17. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Let’s Go!
  • 18. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Solutions
  • 19. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 19 First character of each word concatenated Exercise 1 StringBuilder sb = new StringBuilder(); input.forEach(s -> s.append(s.charAt(0))); String result = sb.toString(); String result = input.stream() .map(s -> s.substring(0, 1)) .reduce("", (a, b) -> a + b);
  • 20. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 20 Map whose keys are first letter, values are sum of lengths Exercise 5 Map<String, Integer> result = new TreeMap(); list.forEach(s -> result.merge(s.substring(0, 1), s.length(), Integer::sum));
  • 21. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 21 Find the length of the longest line Exercise 9 int longest = reader.lines() .mapToInt(String::length) .max() .getAsInt();
  • 22. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 22 Find the longest line Exercise 10 String longest = reader.lines() .max(comparingInt(String::length)) .get();
  • 23. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 23 Select the set of words whose length is greater than the word's position Exercise 11 List<String> result = IntStream.range(0, input.size()) .filter(pos -> input.get(pos).length() > pos) .mpToObj(pos -> input.get(pos)) .collect(toList());
  • 24. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 24 Convert a list of strings into a list of characters Exercise 13 List<Character> result = input.stream() .flatMap(word -> word.chars().mapToObj(i -> (char)i)) .map(c -> (Character)c) ,collect(toList());
  • 25. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 25 Sort unique, lower-cased words by length, then alphabetically within length Exercise 17 List<String> result = reader.lines() .flatMap(line -> Stream.of(line.split(REGEXP))) .map(String::toLowerCase) .distinct() .sorted(comparingInt(String::length) .thenComparing(naturalOrder())) .collect(toList());
  • 26. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 26 Count total number of words and distinct lower-cased words in one pass Exercise 18 LongAdder adder = new LongAdder(); long distinctCount = reader.lines() .flatMap(line -> Stream.of(line.split(REGEXP))) .map(String::toLowerCase) .peek(s -> adder.increment()) .distinct() .count();
  • 27. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. 27 Compute the value of 21! (which needs to use BigInteger) Exercise 19 BigInteger result = IntStream.rangeClosed(1, 21) .mapToObj(n -> BigInteger.valueOf(n)) .reduce(BigInteger.ONE, (m, n) -> m.multiply(n)); T merge(T identity, BiFunction accumulator) === T result = identity; for (T element : this stream) result = accumulator.apply(result, element) return result;
  • 28. Copyright © 2014, Oracle and/or its affiliates. All rights reserved. Graphic Section Divider

Editor's Notes

  1. This is a Title Slide with Java FY15 Theme slide ideal for including the Java Theme with a brief title, subtitle and presenter information. To customize this slide with your own picture: Right-click the slide area and choose Format Background from the pop-up menu. From the Fill menu, click Picture and texture fill. Under Insert from: click File. Locate your new picture and click Insert. To copy the Customized Background from Another Presentation on PC Click New Slide from the Home tab's Slides group and select Reuse Slides. Click Browse in the Reuse Slides panel and select Browse Files. Double-click the PowerPoint presentation that contains the background you wish to copy. Check Keep Source Formatting and click the slide that contains the background you want. Click the left-hand slide preview to which you wish to apply the new master layout. Apply New Layout (Important): Right-click any selected slide, point to Layout, and click the slide containing the desired layout from the layout gallery. Delete any unwanted slides or duplicates. To copy the Customized Background from Another Presentation on Mac Click New Slide from the Home tab's Slides group and select Insert Slides from Other Presentation… Navigate to the PowerPoint presentation file that contains the background you wish to copy. Double-click or press Insert. This prompts the Slide Finder dialogue box. Make sure Keep design of original slides is unchecked and click the slide(s) that contains the background you want. Hold Shift key to select multiple slides. Click the left-hand slide preview to which you wish to apply the new master layout. Apply New Layout (Important): Click Layout from the Home tab's Slides group, and click the slide containing the desired layout from the layout gallery. Delete any unwanted slides or duplicates.
  2. Question: how are we going to get there with real collections?