41
Let it flow Java 8 stream puzzles and more Bhakti Mehta @bhakti_mehta

Let if flow: Java 8 Streams puzzles and more

Embed Size (px)

Citation preview

Page 1: Let if flow: Java 8 Streams puzzles and more

Let it flow Java 8 stream puzzles

and more Bhakti Mehta

@bhakti_mehta

Page 2: Let if flow: Java 8 Streams puzzles and more

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

Page 3: Let if flow: Java 8 Streams puzzles and more

My  recent  book  

Page 4: Let if flow: Java 8 Streams puzzles and more

Previous  book  

Page 5: Let if flow: Java 8 Streams puzzles and more

Blue  Jeans  Network  

Page 6: Let if flow: Java 8 Streams puzzles and more

Evolution  of  Java  O Java 8 has myriad of features O Most prominent are lamdas and streams API O Functional style to Java

Page 7: Let if flow: Java 8 Streams puzzles and more

Streams  O Abstraction not a datastructure O Can transform data O Value in motion O Functional style will affect all collections O Automatic parallelism

Page 8: Let if flow: Java 8 Streams puzzles and more

Collections  in  Java  8  

Contains whole data structure Eager computation

Page 9: Let if flow: Java 8 Streams puzzles and more

Streams  in  Java  8  

Computed on demand Just in time Lazily constructed collection

Page 10: Let if flow: Java 8 Streams puzzles and more

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); }

Page 11: Let if flow: Java 8 Streams puzzles and more

Stream  or  loop    We write List people = … Set shortCities = people.stream() .map(Person::getCity) .filter(c -> c.getName().length() < 5) .collect(toSet());

Page 12: Let if flow: Java 8 Streams puzzles and more

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 readable Composable

operations Can be made parallel

Page 13: Let if flow: Java 8 Streams puzzles and more

Power  of  Stream  O Streams provide the power to write compose

functions and data flows through the functions

Page 14: Let if flow: Java 8 Streams puzzles and more

Components  when  working  with  streams  

Page 15: Let if flow: Java 8 Streams puzzles and more

Intermediate  operations  

filter map

limit sorted

distinct

Page 16: Let if flow: Java 8 Streams puzzles and more

Terminal  operations  

forEach

collect

reduce

Page 17: Let if flow: Java 8 Streams puzzles and more

Map  

function

Page 18: Let if flow: Java 8 Streams puzzles and more

FlatMap  

Page 19: Let if flow: Java 8 Streams puzzles and more

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);

Page 20: Let if flow: Java 8 Streams puzzles and more

FlatMap  sample   List<String> teamLanguages = team.stream(). map(d -> d.getLanguages()). flatMap(l -> l.stream()). collect(Collectors.toList()); returns [“scala”,”go”,”java”]

Page 21: Let if flow: Java 8 Streams puzzles and more

Quiz  

Given a list of numbers return the Squares

Given [1,2,3,4] return [1,4,9,16]

Page 22: Let if flow: Java 8 Streams puzzles and more

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());

Page 23: Let if flow: Java 8 Streams puzzles and more

Filter  

Shape:: isSquare()

Page 24: Let if flow: Java 8 Streams puzzles and more

Group  Grouping

map

Fish Reptiles Mammals

Page 25: Let if flow: Java 8 Streams puzzles and more

Group  Grouping

map

Fish Reptiles Mammals

Stream

Dolphin

Classify

Page 26: Let if flow: Java 8 Streams puzzles and more

Grouping   Map<Animal.Category, List<Animal>> animalsByCategory = animals.stream(). collect(groupingBy(Animal::getCategory)); {Mammals=[Dolphin, Cat, Dog], Fish=[Ray, Shark], Reptiles=[Alligator, Crocodile]}

Page 27: Let if flow: Java 8 Streams puzzles and more

Getting  a  count      Map<Animal.Category, List<Animal>> animalsByCategory = animals.stream(). collect(groupingBy(Animal::getCategory, counting())); {Mammals=2, Fish=2, Reptiles=2}

Page 28: Let if flow: Java 8 Streams puzzles and more

I

Imperative  style  Iterate through the animals Classify in various categories Get counts of each

cumbersome

Verbose

Page 29: Let if flow: Java 8 Streams puzzles and more

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

Page 30: Let if flow: Java 8 Streams puzzles and more

Via  Filtering  List<Item> seafood = menu.stream().filter (Item::isSeaFood).collect(toList()); gives [spicy shrimp, catfish]

Page 31: Let if flow: Java 8 Streams puzzles and more

Multilevel  partitioning  partitioningBy collector can be used in combination with other partioningBy collections to get multi level partitioning

Page 32: Let if flow: Java 8 Streams puzzles and more

Quiz  Is this valid sample?

menu.stream().collect

(partitioningBy

(Item::isSeaFood()

,partitioningBy

(d->d.getCalories()>500)));

Page 33: Let if flow: Java 8 Streams puzzles and more

Quiz  Is this valid sample?

menu.stream().collect

(partitioningBy

(Item::isSeaFood()

,partitioningBy

(d->d.getCalories()>500)));

Page 34: Let if flow: Java 8 Streams puzzles and more

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) .map(String::toUpperCase) .distinct() .collect(toList()));

Page 35: Let if flow: Java 8 Streams puzzles and more

Infinite  stream  O Stream<Integer> evenNumbers =

Stream.iterate(0, n -> n + 2);

Page 36: Let if flow: Java 8 Streams puzzles and more

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

Page 37: Let if flow: Java 8 Streams puzzles and more

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

Page 38: Let if flow: Java 8 Streams puzzles and more

Summary  O Great step by Java 8 towards supporting FP O Use FP and OoP together

Page 39: Let if flow: Java 8 Streams puzzles and more

Use  Streams  and  prosper  

Page 40: Let if flow: Java 8 Streams puzzles and more

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/

Page 41: Let if flow: Java 8 Streams puzzles and more

Questions  O Twitter: @bhakti_mehta