1Z0-819 Stream API 4 — Questions and Answers
Question 1: Which collector creates an unmodifiable list in Java 10+?
- Collectors.toList()
- Collectors.toUnmodifiableList() (Correct answer)
- Collectors.toCollection(ArrayList::new)
- List.of(stream.toArray())
Correct answer: Collectors.toUnmodifiableList()
Collectors.toUnmodifiableList() was introduced in Java 10 and returns an unmodifiable List.
Question 2: What happens when you call a terminal operation on a stream that has already been consumed?
- It returns an empty stream
- It returns Optional.empty()
- It throws IllegalStateException (Correct answer)
- It silently produces no output
Correct answer: It throws IllegalStateException
Streams can only be consumed once; calling a second terminal operation throws IllegalStateException: stream has already been operated upon or closed.
Question 3: Which of the following correctly creates a parallel stream from a List?
- list.stream().parallel()
- list.parallelStream()
- Both A and B (Correct answer)
- Stream.parallelOf(list)
Correct answer: Both A and B
Both list.stream().parallel() and list.parallelStream() produce an equivalent parallel stream.
Question 4: What does flatMap() do differently from map()?
- map() handles null values; flatMap() does not
- flatMap() flattens a stream of streams into a single stream (Correct answer)
- flatMap() applies the function in parallel
- flatMap() requires a BinaryOperator
Correct answer: flatMap() flattens a stream of streams into a single stream
flatMap() applies a function that returns a Stream for each element and then flattens all resulting streams into one.
Question 5: What is the return type of Stream<T>.collect(Collectors.toMap(k, v))?
- Map<K,V> (Correct answer)
- HashMap<K,V>
- Optional<Map<K,V>>
- LinkedHashMap<K,V>
Correct answer: Map<K,V>
Collectors.toMap() returns a Map<K,V> (the concrete type is unspecified but typically HashMap).
Question 6: Which statement correctly describes a short-circuit terminal operation?
- It terminates stream processing early when the result can be determined (Correct answer)
- It skips null elements automatically
- It processes elements in reverse order
- It closes the stream without consuming any elements
Correct answer: It terminates stream processing early when the result can be determined
Short-circuit terminal operations like findFirst(), anyMatch(), and allMatch() can stop processing as soon as a definitive result is found.
Question 7: What does Stream.of(1, 2, 3).mapToInt(Integer::intValue).boxed() return?
- IntStream
- Stream<Integer> (Correct answer)
- List<Integer>
- Stream<int>
Correct answer: Stream<Integer>
boxed() on an IntStream converts each int to Integer and returns a Stream<Integer>.
Which collector creates an unmodifiable list in Java 10+?