2. Synopsis
In this workshop you'll learn how to use Streams in Java, and why they're great!
Some brief introductory slides will be followed by a hands-on workshop, in
which you'll write your own Streams-based code to solve problems.
Prerequisites:
● Basic Java knowledge
● A Java 8 development environment
3. What is a stream?
● An alternative to conventional iteration.
● Using a stream, you can process data in a declarative way similar to SQL
statements.
● A pipeline of functions that can be evaluated.
● A flow of objects that be filtered, transformed, collected.
4. Example of a stream
List redWidgets = widgets.stream()
.filter(w -> w.getColor() == RED)
.collect(Collectors.toList());
5. What is a stream not?
● Not a data structure
● Should not mutate data
6. Why use them?
● Easier to read and comprehend
● Usually leads to shorter code
● Can bring parallelisation easily
● Gives you a vocabulary to solve problems, reducing errors
● Reduces temporary variable use
7. Operations
● Intermediate operators return streams eg map, filter, distinct
● Terminal operators return concrete types or produce a side effect eg
collect, forEach, sum
8. Example of a stream again
List redWidgets = widgets.stream()
.filter(w -> w.getColor() == RED)
.collect(Collectors.toList());
9. Lambdas
● Lambda expressions are otherwise known as anonymous functions
● They are not bound to identifiers
● They produce compact code
nameList.map(n -> System.out.println(“Hello “ + n));
10. Method References
● Method references are references to methods!
● They let us refer to a preexisting method
nameList.map(System.out::println)
27. More collectors
// Compute sum of salaries of employee
int total = employees.stream()
.collect(Collectors.summingInt(Employee::getSalary)));
// Partition students into passing and failing
Map<Boolean, List<Student>> passingFailing =
students.stream()
.collect(Collectors.partitioningBy(s -> s.getGrade() >= PASS_THRESHOLD));
28. Gotchas
● Parallel streams use a globally shared thread pool.
● Stack traces are harder to read.
● Performance