Welcome to the third article in my series on preparing for the Java 21 certification.
Over the next several posts, we’ll walk through the most important language changes, APIs, and tricky details you’ll need to know for the exam.
In this article, we’ll focus on Java Streams. Streams were first introduced in Java 8, but they’ve continued to evolve. For example, Java 9 added the takeWhile
and dropWhile
methods. The question is: have you already mastered them?
To make things practical, we’ll analyze a question in the style of the certification exam.
❓ Question
What is the output from this code?
public static void main(String[] args) {
List.of(2, 4, 5, 6, 7, 8, 9)
.stream()
.takeWhile(n -> n < 5)
.dropWhile(n -> n % 2 != 0)
.forEach(System.out::print); //LINE 1
System.out.println();
int sum = List.of(1, 1, 2, 3, 4, 4, 5, 5, 5)
.parallelStream()
.distinct()
.sorted()
.reduce(0, (a, b) -> a + b);
System.out.println("Sum = " + sum); //LINE 2
}
A) 30
B) 15
C) 24
D) 2468
E) The output from line 2 is unpredictable.
🧠 Explaining the problem:
takeWhile
stops on the first failure, not filtering all non-matching elements.dropWhile
skips elements until the predicate fails, then includes the rest.Using
distinct()
works fine withparallelStream()
makes the result deterministic, so the sum is always 15.
✅ Correct Answer
B) 15
C) 24
Did you get it right? Don’t worry if you missed some; The goal here is to expose you to several tricky details that often show up in the Java 21 certification exam.
⚡ Next in this series: we’ll dive into custom serialization with writeObject
and readObject
.
📬 Stay tuned:
If you don’t want to miss the upcoming parts of this Java 21 Certification series, hit the Subscribe button below.
Without takeWhile, dropWhile would`ve tricked me! Lol.
Thanks for sharing!