Java / Java 21 Interview Questions
What Stream API improvements were introduced in Java 9 through Java 21?
The Stream API has been incrementally enhanced since Java 9. Knowing which methods are available and when they arrived is frequently tested.
| Method | Since | Description |
|---|---|---|
| takeWhile(Predicate) | 9 | Takes elements while predicate is true, then stops |
| dropWhile(Predicate) | 9 | Drops elements while predicate is true, then takes rest |
| iterate(seed, hasNext, next) | 9 | Finite iterate — 3-arg form with a terminating predicate |
| ofNullable(T) | 9 | Stream of 0 or 1 elements (empty if null) |
| Stream.of(T...) | 9 | Already existed; ofNullable is the new addition |
| Collectors.teeing(d1, d2, merger) | 12 | Collect into two downstreams, merge results |
| toList() | 16 | Unmodifiable List directly from stream (vs Collectors.toList()) |
| mapMulti(BiConsumer) | 16 | Flexible flat-map alternative |
| Stream.gather(Gatherer) | 22 preview | Custom intermediate operations (post-21) |
// takeWhile / dropWhile — Java 9
List.of(1, 2, 3, 4, 5, 1, 2)
.stream()
.takeWhile(n -> n < 4) // [1, 2, 3] — stops at first failure
.toList();
// 3-argument iterate — finite sequence
Stream.iterate(1, n -> n <= 100, n -> n * 2) // 1 2 4 8 ... 64
.toList();
// ofNullable — avoids NPE in flatMap chains
Stream.ofNullable(maybeNull) // empty stream if null, else stream of one
.map(String::toUpperCase)
.findFirst();
// Collectors.teeing — Java 12
record Stats(long count, double sum) {}
Stats s = numbers.stream().collect(
Collectors.teeing(
Collectors.counting(),
Collectors.summingDouble(Double::doubleValue),
Stats::new
));
// toList() — Java 16
List names = people.stream().map(Person::name).toList();
// returns an UNMODIFIABLE list — names.add("x") throws UnsupportedOperationException
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
