Core Java Advanced LiveLessons

Streams

Slide navigation: Forward with space bar, → arrow key, or PgDn. Backwards with ← or PgUp.

.jpg

Copyright © Cay S. Horstmann 2016

Understand the stream concept and its benefits

From Iterating to Stream Operations

jshell

import java.util.stream.*;
import java.nio.file.*;
Stream<String> words = Files.lines(Paths.get("/usr/share/dict/words"));
long count = words.filter(w -> w.length() > 12).count();

What Is a Stream?

Stream Workflow

  1. Create a stream.
  2. Transform with intermediate operations.
  3. Produce result with terminal operation.

Be able to create streams

Stream Creation

Infinite Streams

API Methods that Yield Streams

lesson02/creating

Java 9 News Flash - Creating Streams

.png

Transform streams into other streams

Transforming Streams

flatMap

lesson02/transforming

Extracting Substreams and Concatenating Streams

Other Stream Transformations

Know how to get answers from stream data

Simple Reductions

jshell

import java.util.stream.*;
import java.nio.file.*;

Stream<String> words() throws IOException {
   return Files.lines(Paths.get("/usr/share/dict/words"));
}

words().filter(w -> w.length() > 12).max(String::compareToIgnoreCase);

words().filter(s -> s.startsWith("Qu")).findFirst();

Work with the Optional type

The Optional Type

How Not to Work with Optional Values

Creating Optional Values

Composing Optional Value Functions with flatMap

lesson02/optional

Java 9/10 News Flash - Optional

.png

Optional Java 9 News

Optional Cheat Sheet

Optional Code Smells

Place stream results into collections and maps

Collecting Results

Using Collectors

lesson02/collecting

Collecting into Maps

Grouping and Partitioning

jshell

Stream<Locale> locales() { return Stream.of(Locale.getAvailableLocales()); }

locales().collect(Collectors.toMap(Locale::toString, Locale::getDisplayLanguage))

locales().collect(Collectors.toMap(Locale::getCountry, Locale::getDisplayLanguage))
    // Exception—duplicate keys

Map<String, List<Locale>> countryToLocales = locales().collect(
    Collectors.groupingBy(Locale::getCountry));
countryToLocales.get("CH")
    // See http://archive.ethnologue.com/15/show_language.asp?code=gsw

Downstream Collectors

lesson02/downstream

Java 9/10 News Flash - Collectors

.png

Understand the concept of reduction operations

Reduction Operations

Complex Reductions

Work with streams of primitive type values

Primitive Type Streams

Creating Primitive Type Streams

Primitive Type Stream Methods

jshell

IntStream.range(0, 10).map(n -> n * n).forEach(System.out::println)
new Random().ints().limit(1000).toArray()

String hello = "Hello \uD83D\uDE3B";
Arrays.toString(hello.codePoints().toArray())

new Random().ints().map(n -> n % 100).limit(1000).max()
new Random().ints().map(n -> n % 100).limit(1000).summaryStatistics()

Speed up stream operations with parallel streams

Parallel Streams

Ordering

lesson02/parallel

Java 9 News Flash - Files.lines

.png