Sub topic 3
Combining Elements with reduce
This chapter covers the more advanced stream tools. Each one gets a short explanation, and one program at the end shows most of them working.
Combining Elements with reduce
A reduction combines all the elements of a stream into one value. reduce(0, Integer::sum) starts from 0, which is called the identity value, and adds each element to the running total.
Flattening Nested Data with flatMap
flatMap turns each element into a small stream of its own. It then joins all of those small streams into one. You can use it to turn a list of lists into one flat list.
Grouping and Partitioning Data
Collectors.groupingBy puts elements into groups by a key, such as word length. Collectors.partitioningBy always makes exactly two groups, true and false.
Working with IntStream, LongStream, and DoubleStream
A primitive stream holds plain int, long, or double values. It skips boxing, which means wrapping a number in an object like Integer. Primitive streams also have built-in sum() and average() methods.
Common Stream Mistakes and How to Avoid Them
- You can use a stream only once. If you call a second terminal operation on it, Java throws
IllegalStateException. - Don't change outside variables inside a lambda. Collect the results instead.
Infinite Streams with iterate and generate
Stream.iterate(1, n -> n * 2) never ends on its own. Stream.generate doesn't either. Add limit(n) to make the stream finite.
Newer Additions: takeWhile, dropWhile, Stream.toList, and More
takeWhilekeeps elements until the first one that fails the test.dropWhileskips elements until the first one that fails the test, then keeps the rest.toList()returns a list you cannot change. It needs Java 16 or later.
Parallel Streams: When They Help and When They Hurt
parallelStream() splits the work across CPU cores. It helps with large amounts of data and slow, independent work. It hurts with small data, shared state, or tasks where order matters.
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class AdvancedTour {
public static void main(String[] args) {
List<Integer> numbers = List.of(1, 2, 3, 4, 5);
System.out.println(numbers.stream().reduce(0, Integer::sum)); // 15
List<List<Integer>> nested = List.of(List.of(1, 2), List.of(3));
System.out.println(nested.stream().flatMap(List::stream).toList()); // [1, 2, 3]
List<String> words = List.of("apple", "bean", "cherry", "date", "fig");
Map<Integer, Long> byLength = words.stream()
.collect(Collectors.groupingBy(String::length, TreeMap::new, Collectors.counting()));
System.out.println(byLength); // {3=1, 4=2, 5=1, 6=1}
System.out.println(IntStream.rangeClosed(1, 5).map(i -> i * i).sum()); // 55
System.out.println(Stream.iterate(1, n -> n * 2).limit(5).toList()); // [1, 2, 4, 8, 16]
System.out.println(List.of(1, 2, 3, 10, 4).stream()
.takeWhile(n -> n < 5).toList()); // [1, 2, 3]
}
}Exercise
What does List.of(1, 2, 3, 10, 4).stream().dropWhile(n -> n < 5).toList() return?
Show answer
[10, 4]. It skips 1, 2, and 3. It stops skipping at 10, the first element that fails the test, and keeps everything from there, including 4.
Exercise
Why does Stream.of(2, 3, 4).reduce(1, (a, b) -> a * b) start with 1 instead of 0?
Show answer
1 is the identity value for multiplication. Starting from 0 would make the result 0 every time. Starting from 1 gives 24.