1Z0-819 Stream API 5 — Questions and Answers
Question 1: Which terminal operation must be used if you need the result to maintain encounter order in a parallel stream?
- forEach()
- forEachOrdered() (Correct answer)
- peek()
- findAny()
Correct answer: forEachOrdered()
forEachOrdered() respects the encounter order even in parallel streams, unlike forEach() which may process elements in any order.
Question 2: What does Collectors.summarizingInt(ToIntFunction) produce?
- An Integer sum
- An IntSummaryStatistics object (Correct answer)
- An OptionalInt
- A Map of statistics
Correct answer: An IntSummaryStatistics object
summarizingInt() collects count, sum, min, max, and average into an IntSummaryStatistics instance.
Question 3: Which method creates a Stream by reading lines from a file and is defined in java.nio.file.Files?
- Files.newStream()
- Files.lines() (Correct answer)
- Files.readAllLines()
- Files.newBufferedReader().stream()
Correct answer: Files.lines()
Files.lines(Path) returns a lazily-populated Stream<String> of lines from the file.
Question 4: What is the difference between Stream.anyMatch() and Stream.allMatch() when the stream is empty?
- Both return true
- anyMatch returns false; allMatch returns true (Correct answer)
- anyMatch returns true; allMatch returns false
- Both return false
Correct answer: anyMatch returns false; allMatch returns true
On an empty stream, anyMatch() returns false (vacuously no element satisfies the predicate) and allMatch() returns true (vacuously all elements satisfy).
Question 5: Which collector can be used to produce a Map<Boolean, List<T>> from a stream?
- Collectors.groupingBy()
- Collectors.toMap()
- Collectors.partitioningBy() (Correct answer)
- Collectors.collectingAndThen()
Correct answer: Collectors.partitioningBy()
partitioningBy(Predicate) always produces a two-entry Map<Boolean, List<T>> keyed on true and false.
Question 6: What does the following return? Stream.of("hello","world").map(String::toUpperCase).collect(Collectors.joining("-"))
- HELLO-WORLD (Correct answer)
- hello-world
- [HELLO-WORLD]
- HELLOWORLD
Correct answer: HELLO-WORLD
map(String::toUpperCase) converts each string to uppercase; joining("-") concatenates them with a hyphen delimiter.
Question 7: Which of the following best describes a lazy intermediate operation in the Stream API?
- It runs on a background thread
- It is not executed until a terminal operation is invoked (Correct answer)
- It caches its results for reuse
- It skips elements that don't match a predicate
Correct answer: It is not executed until a terminal operation is invoked
Intermediate operations like filter() and map() are lazy — they build a pipeline description but do no work until a terminal operation triggers processing.
Which terminal operation must be used if you need the result to maintain encounter order in a parallel stream?