Operations Flashcards
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>
Flattens nested structures (e.g., List<List<T>>) into a single stream.</T>
Stream<List<Integer>> stream = Stream.of(List.of(1, 2), List.of(3, 4));
//create a stream out of each list before flattening them. That means each element of the original stream was a collection to which i can run stream method
stream.flatMap(List::stream).forEach(System.out::println); // Output: 1, 2, 3, 4</Integer>
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>
Stream<Integer> stream = Stream.of(1, 2, 3);
stream.peek(System.out::println).map(n -> n * n).forEach(System.out::println);
Stream<Integer> stream = Stream.of(1, 2, 3);
stream.peek(System.out::println).map(n -> n * n).forEach(System.out::println);
// Output:
// 1
// 1
// 2
// 4
// 3
// 9</Integer></Integer>