SlideShare a Scribd company logo
Let it flow Java
8 stream puzzles
and more
Bhakti Mehta
@bhakti_mehta
Introduction	
  
O  Senior Software Engineer at Blue Jeans
Network
O Worked at Sun Microsystems/Oracle for 13
years
O Committer to numerous open source projects
including GlassFish Application Server
My	
  recent	
  book	
  
Previous	
  book	
  
Blue	
  Jeans	
  Network	
  
Evolution	
  of	
  Java	
  
O Java 8 has myriad of features
O Most prominent are lamdas and streams API
O Functional style to Java
Streams	
  
O Abstraction not a datastructure
O Can transform data
O Value in motion
O Functional style will affect all collections
O Automatic parallelism
Collections	
  in	
  Java	
  8	
  
Contains whole data structure
Eager computation
Streams	
  in	
  Java	
  8	
  
Computed on demand
Just in time
Lazily constructed collection
Stream	
  or	
  loop	
  	
  
GET the shortest list of cities of people
Instead of
List people = …
Set shortCities = new HashSet<>();
for (Person p : people) {
City c = p.getCity();
if (c.getName().length() < 5 ) {
shortCities.add(c);
}
Stream	
  or	
  loop	
  	
  
We write
List people = …
Set shortCities = people.stream()
.map(Person::getCity)
.filter(c -> c.getName().length() < 5)
.collect(toSet());
Stream	
  or	
  loop	
  	
  
We write
List people = …
Set shortCities = people.stream()
.map(Person::getCity)
.filter(c -> c.getName().length() < 5)
.collect(toSet());
More
concise
More
readableComposable
operationsCan be made
parallel
Power	
  of	
  Stream	
  
O Streams provide the power to write compose
functions and data flows through the
functions
Components	
  when	
  working	
  
with	
  streams	
  
Intermediate	
  operations	
  
filter map
limitsorted
distinct
Terminal	
  operations	
  
forEach
collect
reduce
Map	
  
function
FlatMap	
  
FlatMap	
  sample	
  
public class Teammate {
private Set<String> languages;
Set<String> getLanguages() {
return languages;
}
List<Teammate> team = new ArrayList<>();
Teammate dev1 = new Teammate();
dev1.addLanguage("scala");
dev1.addLanguage(“go”);
Teammate dev2 = new Teammate();
dev2.addLanguage("java");
team.add(dev1);
team.add(dev2);
FlatMap	
  sample	
  
List<String> teamLanguages = team.stream().
map(d -> d.getLanguages()).
flatMap(l -> l.stream()).
collect(Collectors.toList());
returns
[“scala”,”go”,”java”]
Quiz	
  
Given a list of numbers return the Squares
Given [1,2,3,4] return [1,4,9,16]
Quiz	
  
Given a list of numbers return the Squares
Given [1,2,3,4] return [1,4,9,16]
List<Integer>numbers = Arrays.asList(1,2,3,4);
List<Integer> squares = numbers.stream().map
(n->n*n).collect(toList());
Filter	
  
Shape:: isSquare()
Group	
  
Grouping
map
Fish ReptilesMammals
Group	
  
Grouping
map
Fish ReptilesMammals
Stream
Dolphin
Classify
Grouping	
  
Map<Animal.Category, List<Animal>>
animalsByCategory = animals.stream().
collect(groupingBy(Animal::getCategory));
{Mammals=[Dolphin, Cat, Dog], Fish=[Ray, Shark],
Reptiles=[Alligator, Crocodile]}
Getting	
  a	
  count	
  	
  	
  
Map<Animal.Category, List<Animal>> animalsByCategory
= animals.stream().
collect(groupingBy(Animal::getCategory, counting()));
{Mammals=2, Fish=2, Reptiles=2}
I
Imperative	
  style	
  
Iterate through the animals
Classify in various categories
Get counts of each
cumbersome
Verbose
Partitioning	
  
Map<Boolean, List<Item>> partitionedMenu =
menu.stream().collect
(partitioningBy(Item::isSeaFood));
{ false= [brocolli chicken, orange chicken],
true=[spicy shrimp, catfish]}
Getting seafood from the menu
Via	
  Filtering	
  
List<Item> seafood = menu.stream().filter
(Item::isSeaFood).collect(toList());
gives
[spicy shrimp, catfish]
Multilevel	
  partitioning	
  
partitioningBy collector can be used in
combination with other partioningBy
collections to get multi level partitioning
Quiz	
  
Is this valid sample?
menu.stream().collect
(partitioningBy
(Item::isSeaFood()
,partitioningBy
(d->d.getCalories()>500)));
Quiz	
  
Is this valid sample?
menu.stream().collect
(partitioningBy
(Item::isSeaFood()
,partitioningBy
(d->d.getCalories()>500)));
Composability	
  
O Get the unique surnames in uppercase of the
first 15 book authors that are 50 years old
or older
O library.stream() .map(book ->
book.getAuthor()) .filter(author ->
author.getAge() >=
50) .limit(15) .map(Author::getSurname) .ma
p(String::toUpperCase) .distinct() .collect(toLi
st()));
Infinite	
  stream	
  
O Stream<Integer> evenNumbers =
Stream.iterate(0, n -> n + 2);
Parallel	
  streams	
  
O Parallel streams = simple concurrency
O Parallel stream splits its elements in multiple
chunks processing each chunk on a
different thread
O Potentially can use N cores => Nx
speedup
Parallel	
  Streams	
  
O Check the benchmark using sequential and
parallel streams
O Limit and findFirst may be expensive in
parallel stream as they rely on the odrder of
the elements. Use findAny if you are not
constrained by the order
Summary	
  
O Great step by Java 8 towards supporting FP
O Use FP and OoP together
Use	
  Streams	
  and	
  prosper	
  
Resources	
  
O http://blog.fileburst.com/wp-content/
uploads/2012/10/Online-Streaming-
Movies.png
O http://zeroturnaround.com/rebellabs/java-8-
streams-cheat-sheet/
Questions	
  
O Twitter: @bhakti_mehta

More Related Content

What's hot (19)

DOC
Laboratory activity 3 b3
Jomel Penalba
 
PDF
Basic and logical implementation of r language
Md. Mahedi Mahfuj
 
PPT
Functional programming with_scala
Raymond Tay
 
PDF
01. haskell introduction
Sebastian Rettig
 
PDF
JAVA PROGRAMMING - The Collections Framework
Jyothishmathi Institute of Technology and Science Karimnagar
 
PDF
The Ring programming language version 1.5.3 book - Part 22 of 184
Mahmoud Samir Fayed
 
PPT
Sql
tech4us
 
KEY
R for Pirates. ESCCONF October 27, 2011
Mandi Walls
 
PDF
Vertica mpp columnar dbms
Zvika Gutkin
 
PDF
Scala parallel-collections
Knoldus Inc.
 
PDF
Is there a perfect data-parallel programming language? (Experiments with More...
Julian Hyde
 
PDF
Lambda Expressions in Java 8
bryanbibat
 
PDF
Type classes 101 - classification beyond inheritance
Alexey Raga
 
PDF
The Ring programming language version 1.10 book - Part 45 of 212
Mahmoud Samir Fayed
 
PDF
Get started with Reason
Nikolaus Graf
 
PDF
NLP on a Billion Documents: Scalable Machine Learning with Apache Spark
Martin Goodson
 
PPTX
Scala case of case classes
VulcanMinds
 
PDF
Tuples All the Way Down
Giovanni Fernandez-Kincade
 
PDF
Pragmatic Real-World Scala (short version)
Jonas Bonér
 
Laboratory activity 3 b3
Jomel Penalba
 
Basic and logical implementation of r language
Md. Mahedi Mahfuj
 
Functional programming with_scala
Raymond Tay
 
01. haskell introduction
Sebastian Rettig
 
JAVA PROGRAMMING - The Collections Framework
Jyothishmathi Institute of Technology and Science Karimnagar
 
The Ring programming language version 1.5.3 book - Part 22 of 184
Mahmoud Samir Fayed
 
Sql
tech4us
 
R for Pirates. ESCCONF October 27, 2011
Mandi Walls
 
Vertica mpp columnar dbms
Zvika Gutkin
 
Scala parallel-collections
Knoldus Inc.
 
Is there a perfect data-parallel programming language? (Experiments with More...
Julian Hyde
 
Lambda Expressions in Java 8
bryanbibat
 
Type classes 101 - classification beyond inheritance
Alexey Raga
 
The Ring programming language version 1.10 book - Part 45 of 212
Mahmoud Samir Fayed
 
Get started with Reason
Nikolaus Graf
 
NLP on a Billion Documents: Scalable Machine Learning with Apache Spark
Martin Goodson
 
Scala case of case classes
VulcanMinds
 
Tuples All the Way Down
Giovanni Fernandez-Kincade
 
Pragmatic Real-World Scala (short version)
Jonas Bonér
 

Viewers also liked (18)

PDF
Devoxx2017
Bhakti Mehta
 
PDF
Con fess 2013-sse-websockets-json-bhakti
Bhakti Mehta
 
PDF
Java 8 puzzlers
Evgeny Borisov
 
PDF
Architecting for Failures in micro services: patterns and lessons learned
Bhakti Mehta
 
PDF
Benchmarking on JVM
Vladimir Tsanev
 
PPT
Java8 bench gc
Hidetomo Morimoto
 
PPTX
Microbenchmarking with JMH
Henri Tremblay
 
PPTX
Resilience planning and how the empire strikes back
Bhakti Mehta
 
PPTX
Expect the unexpected: Anticipate and prepare for failures in microservices b...
Bhakti Mehta
 
PPTX
Real world RESTful service development problems and solutions
Bhakti Mehta
 
ODP
50 tips50minutes
Bhakti Mehta
 
PDF
Expect the unexpected: Prepare for failures in microservices
Bhakti Mehta
 
PPTX
Think async
Bhakti Mehta
 
PDF
Java 8 Stream API. A different way to process collections.
David Gómez García
 
PDF
Sailing with Java 8 Streams
Ganesh Samarthyam
 
PPTX
jDays - Spring Boot under the Hood
Nicolas Fränkel
 
PDF
Blazing Performance with Flame Graphs
Brendan Gregg
 
PDF
Java 8, Streams & Collectors, patterns, performances and parallelization
José Paumard
 
Devoxx2017
Bhakti Mehta
 
Con fess 2013-sse-websockets-json-bhakti
Bhakti Mehta
 
Java 8 puzzlers
Evgeny Borisov
 
Architecting for Failures in micro services: patterns and lessons learned
Bhakti Mehta
 
Benchmarking on JVM
Vladimir Tsanev
 
Java8 bench gc
Hidetomo Morimoto
 
Microbenchmarking with JMH
Henri Tremblay
 
Resilience planning and how the empire strikes back
Bhakti Mehta
 
Expect the unexpected: Anticipate and prepare for failures in microservices b...
Bhakti Mehta
 
Real world RESTful service development problems and solutions
Bhakti Mehta
 
50 tips50minutes
Bhakti Mehta
 
Expect the unexpected: Prepare for failures in microservices
Bhakti Mehta
 
Think async
Bhakti Mehta
 
Java 8 Stream API. A different way to process collections.
David Gómez García
 
Sailing with Java 8 Streams
Ganesh Samarthyam
 
jDays - Spring Boot under the Hood
Nicolas Fränkel
 
Blazing Performance with Flame Graphs
Brendan Gregg
 
Java 8, Streams & Collectors, patterns, performances and parallelization
José Paumard
 
Ad

Similar to Let if flow: Java 8 Streams puzzles and more (20)

PDF
Java 8: more readable and flexible code
WeAreEsynergy
 
PPTX
Java Foundations: Maps, Lambda and Stream API
Svetlin Nakov
 
PPTX
18. Java associative arrays
Intro C# Book
 
PDF
Fp java8
Yanai Franchi
 
PDF
Lambda.pdf
ManishWalia18
 
PPTX
Processing Collections with Java8 Stream APIs
Zameer Ahmed Shaik
 
PPTX
FUNctional Programming in Java 8
Richard Walker
 
PPT
java 8 Hands on Workshop
Jeanne Boyarsky
 
PPTX
Kpi driven-java-development
Anirban Bhattacharjee
 
PDF
Collectors in the Wild
José Paumard
 
PDF
Scala collections api expressivity and brevity upgrade from java
IndicThreads
 
PPTX
Apache Flink Training: DataStream API Part 2 Advanced
Flink Forward
 
ODP
Collections In Scala
Knoldus Inc.
 
PPTX
Java 8 stream and c# 3.5
Quang Trần Duy
 
PDF
Functional aspects of java 8
Jobaer Chowdhury
 
PPT
Functional Programming
Olexandra Dmytrenko
 
PDF
Java Lambda internals with invoke dynamic
Mohit Kumar
 
PDF
Functional Java 8 in everyday life
Andrea Iacono
 
PPT
Google collections api an introduction
gosain20
 
PDF
Will it Blend? - ScalaSyd February 2015
Filippo Vitale
 
Java 8: more readable and flexible code
WeAreEsynergy
 
Java Foundations: Maps, Lambda and Stream API
Svetlin Nakov
 
18. Java associative arrays
Intro C# Book
 
Fp java8
Yanai Franchi
 
Lambda.pdf
ManishWalia18
 
Processing Collections with Java8 Stream APIs
Zameer Ahmed Shaik
 
FUNctional Programming in Java 8
Richard Walker
 
java 8 Hands on Workshop
Jeanne Boyarsky
 
Kpi driven-java-development
Anirban Bhattacharjee
 
Collectors in the Wild
José Paumard
 
Scala collections api expressivity and brevity upgrade from java
IndicThreads
 
Apache Flink Training: DataStream API Part 2 Advanced
Flink Forward
 
Collections In Scala
Knoldus Inc.
 
Java 8 stream and c# 3.5
Quang Trần Duy
 
Functional aspects of java 8
Jobaer Chowdhury
 
Functional Programming
Olexandra Dmytrenko
 
Java Lambda internals with invoke dynamic
Mohit Kumar
 
Functional Java 8 in everyday life
Andrea Iacono
 
Google collections api an introduction
gosain20
 
Will it Blend? - ScalaSyd February 2015
Filippo Vitale
 
Ad

Recently uploaded (20)

PPTX
Element 7. CHEMICAL AND BIOLOGICAL AGENT.pptx
merrandomohandas
 
DOCX
8th International Conference on Electrical Engineering (ELEN 2025)
elelijjournal653
 
PPTX
Snet+Pro+Service+Software_SNET+Pro+2+Instructions.pptx
jenilsatikuvar1
 
PDF
6th International Conference on Machine Learning Techniques and Data Science ...
ijistjournal
 
PDF
International Journal of Information Technology Convergence and services (IJI...
ijitcsjournal4
 
PPTX
Break Statement in Programming with 6 Real Examples
manojpoojary2004
 
PPTX
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
PDF
Unified_Cloud_Comm_Presentation anil singh ppt
anilsingh298751
 
PPTX
Introduction to Design of Machine Elements
PradeepKumarS27
 
PDF
Design Thinking basics for Engineers.pdf
CMR University
 
PPTX
Element 11. ELECTRICITY safety and hazards
merrandomohandas
 
PDF
GTU Civil Engineering All Semester Syllabus.pdf
Vimal Bhojani
 
PDF
Water Design_Manual_2005. KENYA FOR WASTER SUPPLY AND SEWERAGE
DancanNgutuku
 
PDF
Biomechanics of Gait: Engineering Solutions for Rehabilitation (www.kiu.ac.ug)
publication11
 
PPTX
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
PPTX
Day2 B2 Best.pptx
helenjenefa1
 
PPTX
265587293-NFPA 101 Life safety code-PPT-1.pptx
chandermwason
 
PDF
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
PDF
monopile foundation seminar topic for civil engineering students
Ahina5
 
PPTX
artificial intelligence applications in Geomatics
NawrasShatnawi1
 
Element 7. CHEMICAL AND BIOLOGICAL AGENT.pptx
merrandomohandas
 
8th International Conference on Electrical Engineering (ELEN 2025)
elelijjournal653
 
Snet+Pro+Service+Software_SNET+Pro+2+Instructions.pptx
jenilsatikuvar1
 
6th International Conference on Machine Learning Techniques and Data Science ...
ijistjournal
 
International Journal of Information Technology Convergence and services (IJI...
ijitcsjournal4
 
Break Statement in Programming with 6 Real Examples
manojpoojary2004
 
The Role of Information Technology in Environmental Protectio....pptx
nallamillisriram
 
Unified_Cloud_Comm_Presentation anil singh ppt
anilsingh298751
 
Introduction to Design of Machine Elements
PradeepKumarS27
 
Design Thinking basics for Engineers.pdf
CMR University
 
Element 11. ELECTRICITY safety and hazards
merrandomohandas
 
GTU Civil Engineering All Semester Syllabus.pdf
Vimal Bhojani
 
Water Design_Manual_2005. KENYA FOR WASTER SUPPLY AND SEWERAGE
DancanNgutuku
 
Biomechanics of Gait: Engineering Solutions for Rehabilitation (www.kiu.ac.ug)
publication11
 
Solar Thermal Energy System Seminar.pptx
Gpc Purapuza
 
Day2 B2 Best.pptx
helenjenefa1
 
265587293-NFPA 101 Life safety code-PPT-1.pptx
chandermwason
 
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
monopile foundation seminar topic for civil engineering students
Ahina5
 
artificial intelligence applications in Geomatics
NawrasShatnawi1
 

Let if flow: Java 8 Streams puzzles and more