1Z0-819 Stream API 2 — Questions and Answers
Question 1: Which terminal operation on a Stream returns an OptionalInt containing the minimum value?
- Stream.min()
- IntStream.min() (Correct answer)
- Stream.reduce(Integer.MAX_VALUE, Math::min)
- IntStream.findFirst()
Correct answer: IntStream.min()
IntStream.min() returns an OptionalInt with the minimum value of the stream.
Question 2: What does the following produce? Stream.of(1,2,3).map(n -> n * 2).filter(n -> n > 3).count()
- 1
- 2 (Correct answer)
- 3
- 0
Correct answer: 2
After doubling: 2,4,6; filtering >3 yields 4,6; count() returns 2.
Question 3: Which Collector groups elements into a Map where keys are Boolean values?
- Collectors.groupingBy()
- Collectors.partitioningBy() (Correct answer)
- Collectors.toMap()
- Collectors.mapping()
Correct answer: Collectors.partitioningBy()
Collectors.partitioningBy() splits elements into true/false groups based on a Predicate.
Question 4: What is the result of IntStream.range(0, 5).sum()?
- 10 (Correct answer)
- 15
- 5
- 14
Correct answer: 10
IntStream.range(0,5) produces 0,1,2,3,4; their sum is 10.
Question 5: Which method converts a Stream<Optional<String>> to a Stream<String> containing only present values in Java 9+?
- stream.map(Optional::get)
- stream.filter(Optional::isPresent).map(Optional::get)
- stream.flatMap(Optional::stream) (Correct answer)
- stream.mapToObj(Optional::orElse)
Correct answer: stream.flatMap(Optional::stream)
Optional.stream() was added in Java 9, making flatMap(Optional::stream) the idiomatic approach.
Question 6: What does Collectors.joining(", ", "[", "]") produce for Stream.of("a","b","c")?
- a, b, c
- [a, b, c] (Correct answer)
- [a,b,c]
- a,b,c
Correct answer: [a, b, c]
joining with delimiter ", ", prefix "[", and suffix "]" produces [a, b, c].
Question 7: Which statement about Stream.iterate() in Java 9 is correct?
- It only accepts a seed and UnaryOperator
- It can accept a Predicate as a stop condition (Correct answer)
- It always produces an infinite stream
- It is equivalent to Stream.generate()
Correct answer: It can accept a Predicate as a stop condition
Java 9 added a three-argument Stream.iterate(seed, predicate, unaryOperator) that stops when the predicate is false.
Which terminal operation on a Stream returns an OptionalInt containing the minimum value?