Library contents

Java Stream.filter and limit

Filter a stream of seat counts and stop collecting after two matches.

A simple example

Stream.filter and limit

  1. Start with 1, 2, 3, 4
  2. Do this Keep even numbers, stop after one
  3. Result 2
The first matching number fills the one-item limit.

Syntax

Java 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.java

Find 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.

Result[4, 2]
Main.java

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);
    }
}
Output
[4, 2]

Zero counts are skipped. Once two positive counts are collected, the final eight is unnecessary.

Advertisements

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?

Given6 · 2 · 6 · 0
Worked result6 · 2

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?

Given3 · 0 · 8 · 3
Worked result3 · 8

What to watch for

Apply the filter before the limit when you need a fixed number of matching items.

Documentation for Stream.filter and limit