Terminal Operations Flashcards

1
Q

reduce

A

Stream<Integer> stream = Stream.of(1, 2, 3, 4);
int sum = stream.reduce(0, Integer::sum); // Output: 10</Integer>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

collect

A

Accumulates elements into a collection or another result (e.g., List, Set, Map).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

forEach(Consumer<T> action)</T>

A

Performs an action on each element in the stream (e.g., print).
Stream.of(1, 2, 3).forEach(System.out::println);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

forEachOrdered(Consumer<T> action)</T>

A

Same as forEach, but preserves the order in parallel streams.
Stream.of(3, 2, 1).parallel().forEachOrdered(System.out::println);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Terminal Match Operations

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Finding Elements

A

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>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Aggregation Options

A

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>

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Conversion Options

A

Converts the stream elements into an array.
Object[] array = Stream.of(1, 2, 3).toArray(); // Output: [1, 2, 3]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly