- 1.1. From Iterating to Stream Operations
- 1.2. Stream Creation
- 1.3. The filter, map, and flatMap Methods
- 1.4. Extracting Substreams and Combining Streams
- 1.5. Other Stream Transformations
- 1.6. Simple Reductions
- 1.7. The Optional Type
- 1.8. Collecting Results
- 1.9. Collectors
- 1.10. Reduction Operations
- 1.11. Gatherers
- 1.12. Primitive Type Streams
- 1.13. Parallel Streams
1.5. Other Stream Transformations
The distinct method returns a stream that yields elements from the original stream, in the same order, except that duplicates are suppressed. The duplicates need not be adjacent.
Stream<String> uniqueWords
= Stream.of("merrily", "merrily", "merrily", "gently").distinct();
// Only one "merrily" is retained
For sorting a stream, there are several variations of the sorted method. One works for streams of Comparable elements, and another accepts a Comparator. Here, we sort strings so that the longest ones come first:
Stream<String> longestFirst
= words.stream().sorted(Comparator.comparing(String::length).reversed());
As with all stream transformations, the sorted method yields a new stream whose elements are the elements of the original stream in sorted order.
Of course, you can sort a collection without using streams. The sorted method is useful when the sorting process is part of a stream pipeline.
Finally, the peek method yields another stream with the same elements as the original, but a function is invoked every time an element is retrieved. That is handy for debugging:
Object[] powers = Stream.iterate(1.0, p -> p * 2)
.peek(e -> IO.println("Fetching " + e))
.limit(20)
.toArray();
When an element is actually accessed, a message is printed. This way you can verify that the infinite stream returned by iterate is processed lazily.
