Terminal Operations Flashcards
reduce
Stream<Integer> stream = Stream.of(1, 2, 3, 4);
int sum = stream.reduce(0, Integer::sum); // Output: 10</Integer>
collect
Accumulates elements into a collection or another result (e.g., List, Set, Map).
forEach(Consumer<T> action)</T>
Performs an action on each element in the stream (e.g., print).
Stream.of(1, 2, 3).forEach(System.out::println);
forEachOrdered(Consumer<T> action)</T>
Same as forEach, but preserves the order in parallel streams.
Stream.of(3, 2, 1).parallel().forEachOrdered(System.out::println);
Terminal Match Operations
These return a boolean based on conditions applied to the stream.
boolean allEven = Stream.of(2, 4, 6).allMatch(n -> n % 2 == 0);
boolean anyOdd = Stream.of(1, 2, 4).anyMatch(n -> n % 2 != 0); // Output: true
boolean noneNegative = Stream.of(1, 2, 3).noneMatch(n -> n < 0); // Output: true
Finding Elements
Optional<Integer> first = Stream.of(1, 2, 3).findFirst(); // Output: Optional[1]
Optional<Integer> any = Stream.of(1, 2, 3).findAny(); // Output: Optional[1] (or any)</Integer></Integer>
Aggregation Options
long count = Stream.of(1, 2, 3).count(); // Output: 3
Optional<Integer> max = Stream.of(1, 2, 3).max(Integer::compare); // Output: Optional[3]
Optional<Integer> min = Stream.of(1, 2, 3).min(Integer::compare); // Output: Optional[1]</Integer></Integer>
Conversion Options
Converts the stream elements into an array.
Object[] array = Stream.of(1, 2, 3).toArray(); // Output: [1, 2, 3]