Operations Flashcards

1
Q

Stream.filter()

A

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);

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

Stream.map()

A

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);

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

Stream.sorted()

A

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);

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

flatMap(Function<T, Stream<R>> mapper)</R>

A

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>

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

distinct()

A

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>

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

limit(long maxSize)

A

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>

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

skip(long n)

A

Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
stream.skip(2).forEach(System.out::println); // Output: 3, 4, 5</Integer>

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

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

A

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>

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