Question 1
What is printed?
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
System.out.println(Stream.of("fig", "plum", "date")
.filter(s -> s.length() == 4)
.findFirst());
}
}A. Optional[fig]
Applies findFirst to the source rather than the filtered stream; fig has length 3, is dropped by the length == 4 filter, and never reaches the terminal operation.
B. plum
Assumes findFirst returns the element itself, or that println unwraps an Optional; getting the bare value needs .get(), .orElseThrow() or .orElse(...).
C. Optional[plum]Correct answer
filter keeps plum and date (both length 4) and drops fig; findFirst returns the first survivor wrapped in an Optional without unwrapping it, so println calls Optional.toString(), printing Optional[plum].
D. Optional[date]
Assumes findFirst reports the last element still standing; it reports the first and short-circuits as soon as it has one, so plum wins over date.
Explanation
Trace: filter keeps plum and date, both of length 4, and drops fig. findFirst is a short-circuiting terminal operation that returns the first surviving element wrapped in an Optional — it does not unwrap it. System.out.println therefore calls Optional.toString(), whose format is Optional[value], printing Optional[plum].
Why the others are wrong:
plum assumes findFirst returns the element itself, or that println unwraps an Optional. Getting the bare value needs .get(), .orElseThrow() or .orElse(...).
Optional[fig] applies findFirst to the source rather than to the filtered stream; fig has length 3 and never reaches the terminal operation.
Optional[date] assumes the pipeline runs to completion and findFirst reports the last element still standing. It reports the first, and short-circuits as soon as it has one.
Exam tip: every Optional-returning terminal operation — findFirst, findAny, min, max, and the one-argument reduce — prints as Optional[x] or Optional.empty. The reverse trap is the two-argument reduce(identity, accumulator), which returns the bare element type and never an Optional.