OCP Streams and Lambda Expressions 2 — Questions and Answers
Question 1: Which terminal operation returns an OptionalDouble representing the average of a DoubleStream?
- average() (Correct answer)
- mean()
- sum()
- reduce()
Correct answer: average()
DoubleStream.average() is a terminal operation that returns OptionalDouble containing the arithmetic mean of all elements.
Question 2: What does the flatMap() operation do that map() does not?
- It flattens a stream of streams into a single stream (Correct answer)
- It applies a function to each element and returns a new stream of the same size
- It filters elements based on a predicate
- It sorts elements in natural order
Correct answer: It flattens a stream of streams into a single stream
flatMap() maps each element to a stream and then flattens all those streams into a single stream, whereas map() returns one element per input element.
Question 3: Which functional interface is used by Stream.filter()?
- Predicate<T> (Correct answer)
- Function<T,R>
- Consumer<T>
- Supplier<T>
Correct answer: Predicate<T>
Stream.filter() accepts a Predicate<T>, which is a functional interface with a single abstract method test(T t) returning boolean.
Question 4: What is the result of calling Stream.of(1, 2, 3).reduce(0, Integer::sum)?
- 6 (Correct answer)
- Optional[6]
- 0
- Compilation error
Correct answer: 6
reduce(identity, accumulator) returns the result directly (not wrapped in Optional) because the identity element guarantees a value; 0+1+2+3=6.
Question 5: Which of the following creates a lazy infinite stream of random doubles?
- Stream.generate(Math::random) (Correct answer)
- Stream.of(Math::random)
- Stream.iterate(0.0, Math::random)
- DoubleStream.builder().build()
Correct answer: Stream.generate(Math::random)
Stream.generate(Supplier<T>) produces an infinite sequential unordered stream where each element is generated by the provided Supplier.
Question 6: What does Collectors.joining(", ") do when used with Stream.collect()?
- Concatenates stream elements into a single String separated by ", " (Correct answer)
- Groups elements into a Map by a delimiter
- Joins two streams together
- Collects elements into a List joined as comma-separated values
Correct answer: Concatenates stream elements into a single String separated by ", "
Collectors.joining(delimiter) concatenates all CharSequence elements of a stream into a single String with the given delimiter between each element.
Question 7: Which method on Optional executes an action only if a value is present?
- ifPresent(Consumer) (Correct answer)
- orElse(T)
- filter(Predicate)
- map(Function)
Correct answer: ifPresent(Consumer)
Optional.ifPresent(Consumer<T>) invokes the given consumer with the value if present, and does nothing if the Optional is empty.
Which terminal operation returns an OptionalDouble representing the average of a DoubleStream?