Core Java Advanced LiveLessons

Streams

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

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

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

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