Simplifying java with lambdas (short)
-
Upload
richardwarburton -
Category
Technology
-
view
709 -
download
5
description
Transcript of Simplifying java with lambdas (short)
Simplifying with LambdasRichard 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("button clicked"); }});
button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { System.out.println("button clicked"); }});
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 with a single method
public interface ActionListener { public void actionPerformed(ActionEvent event);}
INFERENCE
button.addActionListener(event ->System.out.println("button clicked")
);
public interface ActionListener { public void actionPerformed(ActionEvent event);}
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(asList("A", "B", "HELLO"),collected);
List<String> beginningWithNumbers =
Stream.of("a", "1abc", "abc1")
.filter(value -> isDigit(value.charAt(0)))
.collect(toList());
assertEquals(
asList("1abc"),
beginningWithNumbers);
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 of each band
4. put together a list of these values.
Putting it Together
Set<String> origins =
album.getMusicians()
.filter(artist -> artist.getName().startsWith("The"))
.map(artist -> artist.getNationality())
.collect(toSet());
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());
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
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 valuesmin, maxaverage, sumsummary statisticsjoin together strings
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 & [email protected]/java8lambdas