Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Simplifying java with lambdas (short)

1,118 views

Published on

There's a revolution calling! Lambda expressions are coming in Java 8 but how can developers benefit? We'll go through a series of code examples, that show how to:
Use the new lambda expressions feature
Write more readable and faster collections processing code using the Streams API
Build complex data processing systems with the new collector abstraction
Use lambda expressions in your own code

Published in: Technology
  • Be the first to comment

Simplifying java with lambdas (short)

  1. 1. Simplifying with Lambdas Richard Warburton
  2. 2. What do you mean simple? Streams Collectors Conclusion
  3. 3. Lambda Expressions are here in Java 8!
  4. 4. What can we simplify?
  5. 5. Writing
  6. 6. Reading
  7. 7. Change
  8. 8. Better Libraries through Code as Data
  9. 9. button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { System.out.println("button clicked"); } });
  10. 10. button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { System.out.println("button clicked"); } });
  11. 11. button.addActionListener(?);
  12. 12. button.addActionListener(event -> ?);
  13. 13. button.addActionListener(event -> System.out.println("button clicked") );
  14. 14. String name = getName(); Runnable runnable = () -> System.out.println(“Hello “ + name);
  15. 15. FUNCTIONAL INTERFACES Everything in Java has a type Problem: Need a type to represent a method Solution: Use interfaces with a single method
  16. 16. public interface ActionListener { public void actionPerformed(ActionEvent event); }
  17. 17. INFERENCE button.addActionListener(event -> System.out.println("button clicked") ); public interface ActionListener { public void actionPerformed(ActionEvent event); }
  18. 18. What do you mean simple? Streams Collectors Conclusion
  19. 19. STREAMS Support automated data parallelism Abstraction to build computation pipelines Iterator with inversion of control
  20. 20. int count = 0; for (Artist artist : artists) { if (artist.isFrom("London")) { count++; } } EXTERNAL ITERATION
  21. 21. artists.stream() .filter(artist -> artist.isFrom("London")) .count(); INTERNAL ITERATION
  22. 22. List<String> collected = Stream.of("a", "b", "hello") .map(item -> item.toUpperCase()) .collect(toList()); assertEquals( asList("A", "B", "HELLO"), collected);
  23. 23. List<String> beginningWithNumbers = Stream.of("a", "1abc", "abc1") .filter(value -> isDigit(value.charAt(0))) .collect(toList()); assertEquals( asList("1abc"), beginningWithNumbers);
  24. 24. int sum = Stream.of(1, 2, 3, 4) .reduce(0, (acc, x) -> acc + x); assertEquals(10, sum);
  25. 25. Putting it Together for a given an album, find the nationality of every band playing on that album
  26. 26. Putting it Together 1. get all the artists for an album, 2. figure out which artists are bands, 3. find the nationalities of each band 4. put together a list of these values.
  27. 27. Putting it Together Set<String> origins = album.getMusicians() .filter(artist -> artist.getName().startsWith("The")) .map(artist -> artist.getNationality()) .collect(toSet());
  28. 28. Eager vs Lazy Set<String> origins = album.getMusicians() .filter(artist -> artist.getName().startsWith("The")) .map(artist -> artist.getNationality()) // What’s happened at this point? .collect(toSet());
  29. 29. Parallelism Parallelism no longer means a rewrite of your code Streams support parallelism out of the box call .parallelStream() instead of .stream() Performs well in the right circumstances, but not a panacea
  30. 30. What do you mean simple? Streams Collectors Conclusion
  31. 31. Enter the Collector Collection is mutable reduction Generic API for building up final values Already seen collect(toList())
  32. 32. import static java.util.stream.Collectors.*; collect(toList()); collect(toSet()); collect(toCollection( () -> new TreeSet<>()));
  33. 33. Map<Boolean, List<Artist>> bandsAndSolo = artists.collect(partitioningBy(a -> a.isSolo()));
  34. 34. Map<Artist, List<Album>> albumsByArtist = albums.collect( groupingBy(alb -> alb.getMainMusician()));
  35. 35. Map<Artist, Long> albumsByArtist = albums.collect( groupingBy(alb -> alb.getMainMusician(), counting()));
  36. 36. Recap of Collectors Mutable Reduction A custom collector is just implementing an interface Can collect other values min, max average, sum summary statistics join together strings
  37. 37. What do you mean simple? Streams Collectors Design Patterns Conclusion
  38. 38. How did we simplify?
  39. 39. Behavioural abstraction A method/class which is parameterized by different behaviours.
  40. 40. High Order Functions Functions which take other functions as arguments or return functions.
  41. 41. Writing Avoided repeating basic looping and collections constructs.
  42. 42. Reading Words like map or reduce provide immediate understanding.
  43. 43. Changing Applying the same techniques in your own code reaps huge rewards.
  44. 44. Q & A @richardwarburto insightfullogic.com tinyurl.com/java8lambdas

×