Stream.filter()
The filter() method accepts a Predicate to filter all elements of the stream. This operation is intermediate, enabling us to call another stream operation (e.g. forEach()) on the result.
memberNames.stream().filter((s) -> s.startsWith(“A”))
.forEach(System.out::println);
Stream.map()
The map() intermediate operation converts each element in the stream into another object via the given function
memberNames.stream().filter((s) -> s.startsWith(“A”))
.map(String::toUpperCase)
.forEach(System.out::println);
Stream.sorted()
The sorted() method is an intermediate operation that returns a sorted view of the stream. The elements in the stream are sorted in natural order unless we pass a custom Comparator.
memberNames.stream().sorted()
.map(String::toUpperCase)
.forEach(System.out::println);
flatMap(Function<T, Stream<R>> mapper)</R>
Conceptually, flatMap() performs two steps:
1. Apply the mapper function (which returns a stream) to each element.
2. Flatten all those inner streams into one continuous stream.
List<String> sentences = List.of("hello world", "java streams");
List<String> words = sentences.stream()
.flatMap(sentence -> Arrays.stream(sentence.split(" ")))
.toList();</String></String>
System.out.println(words);
[hello, world, java, streams]
distinct()
Removes duplicate elements from the stream. Equality is determined using equals().
Stream<Integer> stream = Stream.of(1, 2, 2, 3, 3, 3);
stream.distinct().forEach(System.out::println); // Output: 1, 2, 3</Integer>
limit(long maxSize)
Truncates the stream to contain no more than maxSize elements.
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
stream.limit(3).forEach(System.out::println); // Output: 1, 2, 3</Integer>
skip(long n)
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
stream.skip(2).forEach(System.out::println); // Output: 3, 4, 5</Integer>
peek(Consumer<T> action)</T>
Peek lets us view intermediate values between stages. It doesn’t modify the stream — it just lets us see what’s flowing through it.
List<String> names = List.of("Alice", "Bob", "Charlie");
names.stream()
.filter(n -> n.length() > 3)
.peek(n -> System.out.println("After filter: " + n)).map(String::toUpperCase).peek(n -> System.out.println("After map: " + n)).toList();</String>
Output
After filter: Alice
After map: ALICE
After filter: Charlie
After map: CHARLIE