Java SE 8 Programmer II study materials
Java SE 8 Programmer II study resources

Java SE 8 Programmer II: Java Stream API

Java SE 8 Programmer II · Work through your exam, one topic at a time.

All guide sections

Java Stream API

Java Stream API tests building lazy pipelines, choosing intermediate versus terminal operations, and collecting results correctly.

Core rules

  • A stream has a source, zero or more intermediate operations (filter, map, flatMap, distinct, sorted, peek, limit, skip), and one terminal operation (forEach, collect, reduce, count, anyMatch, findFirst, min, max).
  • Intermediate operations are lazy and return a new stream; nothing runs until the terminal operation executes.
  • A stream cannot be reused; doing so throws IllegalStateException.
  • map transforms one element to one element; flatMap transforms each element to a stream and flattens the results.
  • collect(Collectors.groupingBy(classifier)) returns Map<K, List<T>>; a downstream collector such as counting() or mapping() changes the value type. partitioningBy always returns a two-entry Map<Boolean, List<T>>.
  • Primitive streams (IntStream, LongStream, DoubleStream) provide sum(), average(), summaryStatistics(), and boxed().

Worked example

List<String> words = Arrays.asList("a","bb","cc"); Map<Integer,Long> byLen = words.stream().collect(Collectors.groupingBy(String::length, Collectors.counting())); Result: {1=1, 2=2}. The classifier key is the length; counting() counts elements per group. Without the downstream collector the values would be List<String>.

Traps

  • Forgetting the terminal operation means no processing occurs.
  • Reusing a stream after a terminal operation is an error.
  • findFirst() returns Optional; calling get() on empty throws NoSuchElementException.
  • Collectors.toMap throws IllegalStateException on duplicate keys unless a merge function is supplied.
  • sorted() on non-Comparable elements fails unless a Comparator is given.
  • peek is intended for debugging; relying on it for side effects in a short-circuiting pipeline is unsafe.