1Z0-819 Stream API 3 — Questions and Answers
Question 1: What does Stream.of("a","b","c").reduce("", (x,y) -> x + y) return?
- Optional[abc]
- abc (Correct answer)
- a
- Optional.empty()
Correct answer: abc
The two-argument reduce() with an identity value returns the result directly (not wrapped in Optional).
Question 2: Which of the following is a stateful intermediate operation?
- filter()
- map()
- sorted() (Correct answer)
- peek()
Correct answer: sorted()
sorted() must process all elements before emitting any, making it stateful; the others can process elements one at a time.
Question 3: What is the output of Stream.of(3,1,4,1,5).distinct().sorted().findFirst().orElse(-1)?
- 3
- 1 (Correct answer)
- 5
- -1
Correct answer: 1
distinct() gives 3,1,4,5; sorted() gives 1,3,4,5; findFirst() returns Optional[1], orElse(-1) returns 1.
Question 4: Which Collectors method produces a Map<K, Long> counting elements per group?
- Collectors.groupingBy(classifier)
- Collectors.groupingBy(classifier, Collectors.counting()) (Correct answer)
- Collectors.toMap(k, v -> 1L, Long::sum)
- Collectors.counting()
Correct answer: Collectors.groupingBy(classifier, Collectors.counting())
Collectors.groupingBy with a downstream Collectors.counting() produces a Map where each key maps to the count of matching elements.
Question 5: What does Stream.empty() return when collect(Collectors.toList()) is called?
- null
- An empty Optional
- An empty List (Correct answer)
- A List with one null element
Correct answer: An empty List
Stream.empty() has no elements, so collecting to a list produces an empty (non-null) List.
Question 6: Which method should be used to process a stream element for side effects without changing the stream?
- map()
- forEach()
- peek() (Correct answer)
- consume()
Correct answer: peek()
peek() is an intermediate operation designed for side-effect inspection (e.g., debugging) while passing elements downstream unchanged.
Question 7: What is the result of LongStream.rangeClosed(1, 4).average()?
- OptionalLong[2]
- OptionalDouble[2.5] (Correct answer)
- 2.5
- OptionalDouble.empty()
Correct answer: OptionalDouble[2.5]
rangeClosed(1,4) produces 1,2,3,4; average() returns OptionalDouble[2.5].
What does Stream.of("a","b","c").reduce("", (x,y) -> x + y) return?