Simplifying with Lambdas
Richard Warburton
What do you mean simple?
Streams
Collectors
Conclusion
Lambda Expressions are here in Java 8!
What can we simplify?
Writing
Reading
Change
Better Libraries through Code as Data
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.out.println("butto...
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.out.println("butto...
button.addActionListener(?);
button.addActionListener(event -> ?);
button.addActionListener(event ->
System.out.println("button clicked")
);
String name = getName();
Runnable runnable =
() -> System.out.println(“Hello “ + name);
FUNCTIONAL INTERFACES
Everything in Java has a type
Problem: Need a type to represent a method
Solution: Use interfaces wi...
public interface ActionListener {
public void actionPerformed(ActionEvent event);
}
INFERENCE
button.addActionListener(event ->
System.out.println("button clicked")
);
public interface ActionListener {
publ...
What do you mean simple?
Streams
Collectors
Conclusion
STREAMS
Support automated data parallelism
Abstraction to build computation pipelines
Iterator with inversion of control
int count = 0;
for (Artist artist : artists) {
if (artist.isFrom("London")) {
count++;
}
}
EXTERNAL ITERATION
artists.stream()
.filter(artist -> artist.isFrom("London"))
.count();
INTERNAL ITERATION
List<String> collected =
Stream.of("a", "b", "hello")
.map(item -> item.toUpperCase())
.collect(toList());
assertEquals(
a...
List<String> beginningWithNumbers =
Stream.of("a", "1abc", "abc1")
.filter(value -> isDigit(value.charAt(0)))
.collect(toL...
int sum =
Stream.of(1, 2, 3, 4)
.reduce(0, (acc, x) -> acc + x);
assertEquals(10, sum);
Putting it Together
for a given an album, find the nationality of every band
playing on that album
Putting it Together
1. get all the artists for an album,
2. figure out which artists are bands,
3. find the nationalities ...
Putting it Together
Set<String> origins =
album.getMusicians()
.filter(artist -> artist.getName().startsWith("The"))
.map(...
Eager vs Lazy
Set<String> origins =
album.getMusicians()
.filter(artist -> artist.getName().startsWith("The"))
.map(artist...
Parallelism
Parallelism no longer means a rewrite of your code
Streams support parallelism out of the box
call .parallelSt...
What do you mean simple?
Streams
Collectors
Conclusion
Enter the Collector
Collection is mutable reduction
Generic API for building up final values
Already seen collect(toList())
import static java.util.stream.Collectors.*;
collect(toList());
collect(toSet());
collect(toCollection(
() -> new TreeSet<...
Map<Boolean, List<Artist>> bandsAndSolo =
artists.collect(partitioningBy(a -> a.isSolo()));
Map<Artist, List<Album>> albumsByArtist =
albums.collect(
groupingBy(alb -> alb.getMainMusician()));
Map<Artist, Long> albumsByArtist =
albums.collect(
groupingBy(alb -> alb.getMainMusician(),
counting()));
Recap of Collectors
Mutable Reduction
A custom collector is just implementing an interface
Can collect other values
min, m...
What do you mean simple?
Streams
Collectors
Design Patterns
Conclusion
How did we simplify?
Behavioural abstraction
A method/class which is parameterized by
different behaviours.
High Order Functions
Functions which take other functions as
arguments or return functions.
Writing
Avoided repeating basic looping and
collections constructs.
Reading
Words like map or reduce provide
immediate understanding.
Changing
Applying the same techniques in your own
code reaps huge rewards.
Q & A
@richardwarburto
insightfullogic.com
tinyurl.com/java8lambdas
Simplifying java with lambdas (short)
Simplifying java with lambdas (short)
Simplifying java with lambdas (short)
Simplifying java with lambdas (short)
Simplifying java with lambdas (short)
Simplifying java with lambdas (short)
Simplifying java with lambdas (short)
Simplifying java with lambdas (short)
Simplifying java with lambdas (short)
Simplifying java with lambdas (short)
Upcoming SlideShare
Loading in …5
×

Simplifying java with lambdas (short)

916 views
846 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
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
916
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
16
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

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

×