Java Stream.filter and limit
Filter a stream of seat counts and stop collecting after two matches.
A simple example
Stream.filter and limit
- Start with 1, 2, 3, 4
- Do this Keep even numbers, stop after one
- Result 2
Syntax
seats.stream().filter(n -> n > 0).limit(2)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaFind the first two available seats
A booking app must assign a small number of available seats to a customer. Scan the candidates in the required order and stop once enough qualifying places have been found.
class Main {
public static void main(String[] args) throws Exception {
var seats = java.util.List.of(0, 4, 0, 2, 8);
var first = seats.stream().filter(n -> n > 0).limit(2).toList();
System.out.println(first);
}
}
[4, 2]
Zero counts are skipped. Once two positive counts are collected, the final eight is unnecessary.
Count packs on the delivery slip
A loading desk receives four item counts in sequence. The next tray takes only the first two positive quantities. Which quantities reach it?
Review print quantities
A print room records four job quantities, including a cancelled job. The next tray takes only the first two positive quantities. Which quantities reach it?
What to watch for
Apply the filter before the limit when you need a fixed number of matching items.