# Sorting, Cutting and Checking Streams

Put a list of objects in order, cut it into pages, and ask it yes-or-no questions with the stream functions Java developers use every day.

Journeyman · Java · Updated November 16, 2026

By Gregor Dzierzon

## After this lesson you can

- Sort and cut a stream with sorted, Comparator.comparing, reversed, limit and skip
- Check a stream with anyMatch, allMatch and noneMatch, and find the first match with findFirst and orElse

## Key takeaways

- sorted needs a Comparator for your own classes. Comparator.comparing names the value to sort by, and reversed flips the order.
- A method reference such as Product::getUnitPrice means the same as a lambda that only calls that one method.
- limit keeps the first items and skip drops them, so skip followed by limit gives one page of results.
- anyMatch, allMatch and noneMatch answer yes-or-no questions, and stop as soon as they know the answer.
- findFirst gives an Optional, a box that might be empty, and orElse says what to use when it is.

Picture your first week on a team that runs an online grocery store. A data access object (the DAO from [Data Access Objects](https://www.ask-codey.com/lessons/mapping-data-to-models-data-access-objects?course=java-full-stack-bootcamp)) hands you every product as a `List<Product>`. Then the requests start arriving:

- "List the products cheapest first."
- "Show the three most expensive products as premium picks, and the rest in pages of three."
- "Is anything out of stock?"
- "Put the first Seafood product on the specials banner."

You could write every one of these as a loop. In [Common Stream Functions](https://www.ask-codey.com/lessons/what-is-a-stream-common-stream-functions?course=java-full-stack-bootcamp) you met `forEach`, `filter`, `map`, `distinct` and `reduce`. This lesson and the next one add the stream functions Java developers reach for after those, grouped by the job they do. This lesson covers three jobs: putting things in order, cutting a list down, and asking yes-or-no questions. The next lesson, [Counting, Collecting and Flattening Streams](https://www.ask-codey.com/lessons/common-java-stream-functions-collecting?course=java-full-stack-bootcamp), covers counting and math, collecting the results into a `String` or into groups, and lists of lists. For each function you'll see the loop you would write without it, where that loop gets clumsy, and the function that does the same job in a line or two.

## The products we'll work with

Every example in this lesson uses the same eight products from the store. Each one is a `Product` object, a data model like the ones in [Creating Data Models](https://www.ask-codey.com/lessons/objects-from-a-database-creating-data-models?course=java-full-stack-bootcamp), with a constructor (from [What is a Constructor](https://www.ask-codey.com/lessons/working-with-objects-what-is-a-constructor?course=java-full-stack-bootcamp)) and a getter for each field. The setters are left out to keep it short.

```java
public class Product
{
    private String productName;
    private String categoryName;
    private double unitPrice;
    private int unitsInStock;

    public Product(String productName, String categoryName, double unitPrice, int unitsInStock)
    {
        this.productName = productName;
        this.categoryName = categoryName;
        this.unitPrice = unitPrice;
        this.unitsInStock = unitsInStock;
    }

    public String getProductName()
    {
        return productName;
    }

    public String getCategoryName()
    {
        return categoryName;
    }

    public double getUnitPrice()
    {
        return unitPrice;
    }

    public int getUnitsInStock()
    {
        return unitsInStock;
    }
}
```

And the list, in the order the DAO returned it:

```java
List<Product> products = new ArrayList<>();
products.add(new Product("Chai", "Beverages", 18.00, 39));
products.add(new Product("Chang", "Beverages", 19.00, 17));
products.add(new Product("Aniseed Syrup", "Condiments", 10.00, 13));
products.add(new Product("Chef Anton's Gumbo Mix", "Condiments", 21.35, 0));
products.add(new Product("Ikura", "Seafood", 31.00, 31));
products.add(new Product("Konbu", "Seafood", 6.00, 24));
products.add(new Product("Tofu", "Produce", 23.25, 35));
products.add(new Product("Alice Mutton", "Meat/Poultry", 39.00, 0));
```

| Product | Category | Price | Units in stock |
|---|---|---|---|
| Chai | Beverages | 18.00 | 39 |
| Chang | Beverages | 19.00 | 17 |
| Aniseed Syrup | Condiments | 10.00 | 13 |
| Chef Anton's Gumbo Mix | Condiments | 21.35 | 0 |
| Ikura | Seafood | 31.00 | 31 |
| Konbu | Seafood | 6.00 | 24 |
| Tofu | Produce | 23.25 | 35 |
| Alice Mutton | Meat/Poultry | 39.00 | 0 |

Two of them, Chef Anton's Gumbo Mix and Alice Mutton, are out of stock. Keep an eye on them: several examples below find them.

## Sorting: putting products in order

**When you'll use it:** almost every list a user sees is sorted: products by price, students by last name, orders by date.

### The problem: sorted() doesn't know what "in order" means for a product

In [Working with Java Streams](https://www.ask-codey.com/lessons/what-is-a-stream-working-with-java-streams?course=java-full-stack-bootcamp), `sorted()` put a list of names in alphabetical order. Try the same thing on products:

```java
var sortedProducts = products.stream()
        .sorted()
        .toList();
```

It compiles, but when it runs, the program stops with a `ClassCastException` whose message says the product class `cannot be cast to class java.lang.Comparable`.

Here's why. A `String` knows how to put itself in order (alphabetically), and so does an `Integer` (smallest first). In Java's words, they are **Comparable**: they have a built-in, natural order. A `Product` doesn't. Should Chai come before Konbu because of its name, its price or its stock? Java can't guess, so it stops.

Without streams, you would copy the list and write your own sorting loop: compare two neighbors, swap them if they're in the wrong order, and repeat until nothing moves. That's a dozen lines with two nested loops, and every boundary in them is a chance for a mistake.

### Comparator.comparing: tell Java what to sort by

Think of a team photo. The photographer doesn't say "line up"; they say "line up **by height**". That instruction, the rule for deciding which of two people stands first, is what Java calls a **comparator**: an object that compares two items and says which one comes first.

`Comparator.comparing(...)` builds a comparator from the value you want to sort by. You hand it a lambda that takes one item and gives back that value:

```java
var cheapestFirst = products.stream()
        .sorted(Comparator.comparing(product -> product.getUnitPrice()))
        .map(product -> product.getProductName())
        .toList();

// cheapestFirst contains [Konbu, Aniseed Syrup, Chai, Chang, Chef Anton's Gumbo Mix, Tofu, Ikura, Alice Mutton]
```

Read the `sorted` line aloud as "sort the products, comparing them by their unit price". The `->` in the lambda is read "goes to": each `product` goes to its price. Numbers sort smallest first, and `String` values sort alphabetically.

Two details:

- `Comparator` lives in the `java.util` package, so the file needs `import java.util.Comparator;` at the top. IntelliJ offers to add it for you.
- `sorted` doesn't change `products`. The list keeps the order the DAO gave it, and the stream hands you a new, sorted result.

### reversed, and the shortcut called a method reference

Now the manager wants the most expensive products first. A comparator has a `reversed()` method that flips its order, so this looks like the answer:

```java
var priciestFirst = products.stream()
        .sorted(Comparator.comparing(product -> product.getUnitPrice()).reversed())
        .toList();
```

It doesn't compile:

```text
error: cannot find symbol
  symbol:   method getUnitPrice()
  location: variable product of type Object
```

Java works out what type a lambda's parameter is from where the lambda is used. Here, `.reversed()` comes straight after `comparing(...)`, and at that point Java has nothing telling it that `product` is a `Product`, so it treats it as a plain `Object`, which has no `getUnitPrice()` method.

The fix is a **method reference**: `Product::getUnitPrice`. The `::` is read "double colon", and the whole thing reads "Product's getUnitPrice method". It means exactly the same as the lambda `product -> product.getUnitPrice()`: take each product and call its `getUnitPrice()`. Because it names the class, Java knows the type, and `reversed()` works:

```java
var priciestFirst = products.stream()
        .sorted(Comparator.comparing(Product::getUnitPrice).reversed())
        .map(Product::getProductName)
        .toList();

// priciestFirst contains [Alice Mutton, Ikura, Tofu, Chef Anton's Gumbo Mix, Chang, Chai, Aniseed Syrup, Konbu]
```

**When will you use a method reference?** Whenever a lambda does nothing but call one method on its item, like `product -> product.getProductName()`. You'll see them all over professional Java code, and IntelliJ often suggests swapping such a lambda for one. When the lambda does more than call a method, such as a comparison like `product -> product.getUnitsInStock() == 0`, keep the lambda. The rest of this lesson uses both.

### thenComparing: breaking ties

The category page shows the categories in alphabetical order, and within each category, the cheapest product first. That's two rules: first by category, and when two products share a category, by price. `thenComparing` adds the second rule:

```java
var byCategoryThenPrice = products.stream()
        .sorted(Comparator.comparing(Product::getCategoryName)
                .thenComparing(Product::getUnitPrice))
        .map(product -> product.getCategoryName() + ": " + product.getProductName())
        .toList();

byCategoryThenPrice.forEach(line -> System.out.println(line));
```

```text
Beverages: Chai
Beverages: Chang
Condiments: Aniseed Syrup
Condiments: Chef Anton's Gumbo Mix
Meat/Poultry: Alice Mutton
Produce: Tofu
Seafood: Konbu
Seafood: Ikura
```

Notice the two Seafood products: Konbu ($6.00) comes before Ikura ($31.00), even though Ikura came first in the list. The second rule only decides when the first rule ties.

## Cutting: limit and skip

**When you'll use it:** a "top 5" box, a home page that shows the newest three posts, and every list that's split into pages.

### limit: keep the first few

The home page's **premium picks** box shows the three most expensive products. With a loop, you'd sort first, then count as you go and stop at three. Using the `priciestFirst` names from above:

```java
List<String> premiumPicks = new ArrayList<>();
for (String productName : priciestFirst)
{
    if (premiumPicks.size() == 3)
    {
        break;
    }
    premiumPicks.add(productName);
}
```

That works, but the counting and the `break` hide what you meant. `limit(3)` says it directly: let the first three items through and stop.

```java
var premiumPicks = products.stream()
        .sorted(Comparator.comparing(Product::getUnitPrice).reversed())
        .limit(3)
        .map(Product::getProductName)
        .toList();

// premiumPicks contains [Alice Mutton, Ikura, Tofu]
```

When the stream has fewer items than the limit, `limit` lets all of them through. `limit(20)` on eight products gives you the eight.

### skip: drop the first few, for pages of results

Think of search results: page 1 shows results 1 to 3, page 2 shows results 4 to 6, and so on. With a loop over `byName`, the product names in alphabetical order, you'd count positions yourself, and you'd need to stop at the end of the list too:

```java
List<String> pageTwo = new ArrayList<>();
for (int i = 3; i < 6 && i < byName.size(); i++)
{
    pageTwo.add(byName.get(i));
}
```

A loop like that is a common place for an off-by-one mistake. `skip(n)` drops the first `n` items, and `limit` keeps the next ones, so a page is `skip` followed by `limit`:

```java
int pageSize = 3;
int page = 2;

var pageTwo = products.stream()
        .sorted(Comparator.comparing(Product::getProductName))
        .skip((page - 1) * pageSize)
        .limit(pageSize)
        .map(Product::getProductName)
        .toList();

// pageTwo contains [Chang, Chef Anton's Gumbo Mix, Ikura]
```

`(page - 1) * pageSize` is how many products come before the page: none before page 1, three before page 2, six before page 3.

| Page | skip | limit | The names |
|---|---|---|---|
| 1 | 0 | 3 | Alice Mutton, Aniseed Syrup, Chai |
| 2 | 3 | 3 | Chang, Chef Anton's Gumbo Mix, Ikura |
| 3 | 6 | 3 | Konbu, Tofu |

Page 3 has only two names, because only two products are left, and `limit` doesn't complain about that.

The order of the steps matters. `skip(3).limit(3)` drops three and keeps the next three. `limit(3).skip(3)` keeps three, then drops those same three, and gives you an empty list.

## Finding and checking: yes-or-no questions

**When you'll use it:** validation ("is every price above zero?"), warnings ("is anything out of stock?") and lookups ("find the first order that hasn't shipped").

### anyMatch: is there at least one?

Before the morning email goes out, the manager asks: is anything out of stock? With a loop, you'd start with `false` and look for a reason to change your mind:

```java
boolean anyOutOfStock = false;
for (Product product : products)
{
    if (product.getUnitsInStock() == 0)
    {
        anyOutOfStock = true;
        break;
    }
}
```

That's eight lines for one question. `anyMatch` asks it in one: does **any** product match this condition?

```java
boolean anyOutOfStock = products.stream()
        .anyMatch(product -> product.getUnitsInStock() == 0);

// anyOutOfStock is true
```

The lambda inside is a condition, the same kind you give `filter`: it takes one product and answers `true` or `false`. And like the loop's `break`, `anyMatch` stops as soon as it finds a match. Here it stops at Chef Anton's Gumbo Mix, the fourth product, without looking at the rest.

### allMatch and noneMatch

Two more questions of the same shape:

- `allMatch`: does **every** item match? Does every product cost less than $50?
- `noneMatch`: does **no** item match? Is there no Dairy Products product in the list?

```java
boolean allUnder50 = products.stream()
        .allMatch(product -> product.getUnitPrice() < 50);

boolean noDairy = products.stream()
        .noneMatch(product -> product.getCategoryName().equals("Dairy Products"));

// allUnder50 is true, and noDairy is true
```

All three stop early once they know the answer: `allMatch` stops at the first item that fails, and `noneMatch` at the first item that matches.

One surprise is worth knowing before it surprises you in a test. On an **empty** list, `anyMatch` is `false`, because there's nothing to match, but `allMatch` and `noneMatch` are both `true`, because no item broke the rule.

| On an empty list | Gives | Why |
|---|---|---|
| `anyMatch(...)` | `false` | There's no item to match. |
| `allMatch(...)` | `true` | No item failed the condition. |
| `noneMatch(...)` | `true` | No item matched the condition. |

So when an empty list should mean "no", check that the list isn't empty as well as using `allMatch`.

### findFirst and Optional: the first one, if there is one

The specials banner shows the first Seafood product. With a loop, you'd keep the name in a variable that starts as `null` (no value at all) and stop at the first match:

```java
String firstSeafood = null;
for (Product product : products)
{
    if (product.getCategoryName().equals("Seafood"))
    {
        firstSeafood = product.getProductName();
        break;
    }
}
```

The trouble comes when there's no Seafood at all. The variable stays `null`, and the first time the page uses it, such as `firstSeafood.length()`, the program stops with a `NullPointerException`.

Think of a package locker at the post office. You get a locker number, but the locker might hold your package or might be empty, and you look before you reach in. Java's version of that locker is **Optional**: a box that holds one value or nothing. `findFirst()` gives back an `Optional`, so the "maybe nothing" is right there in the type, where you can't forget it.

The most useful thing to do with an `Optional` is `orElse(...)`: take the value out of the box, or, if the box is empty, use this other value instead.

```java
String firstSeafood = products.stream()
        .filter(product -> product.getCategoryName().equals("Seafood"))
        .map(Product::getProductName)
        .findFirst()
        .orElse("Nothing in this category");

String firstDairy = products.stream()
        .filter(product -> product.getCategoryName().equals("Dairy Products"))
        .map(Product::getProductName)
        .findFirst()
        .orElse("Nothing in this category");

// firstSeafood is "Ikura", and firstDairy is "Nothing in this category"
```

Read it aloud: "keep the Seafood products, take their names, find the first one, or else use *Nothing in this category*". Both variables end up holding a real `String`, never `null`.

## Do it: fill the budget picks box

The store's home page has a **Budget picks** box: the cheapest products a shopper can buy today. A product that's out of stock can't be bought, so it never shows in the box, however cheap it is. The marketing team decides how many names fit.

The method gets two values:

- `products`: the store's products, a `List<Product>`. Each `Product` has a name (`getProductName()`), a price (`getUnitPrice()`, a `double`) and the units in stock (`getUnitsInStock()`, an `int`). The class is written for you in the starter: the lesson's `Product` without its category, which the box doesn't need.
- `count`: how many names fit in the box, an `int`, such as `3`.

For example, `budgetPicks(products, 3)` with the lesson's eight products:

```java
List<Product> products = List.of(
        new Product("Chai", 18.00, 39),
        new Product("Chang", 19.00, 17),
        new Product("Aniseed Syrup", 10.00, 13),
        new Product("Chef Anton's Gumbo Mix", 21.35, 0),
        new Product("Ikura", 31.00, 31),
        new Product("Konbu", 6.00, 24),
        new Product("Tofu", 23.25, 35),
        new Product("Alice Mutton", 39.00, 0));
```

| Step | The products |
|---|---|
| Only the products in stock (more than 0 units) | Chai, Chang, Aniseed Syrup, Ikura, Konbu, Tofu |
| Cheapest first | Konbu (6.00), Aniseed Syrup (10.00), Chai (18.00), Chang (19.00), Tofu (23.25), Ikura (31.00) |
| The first 3 | Konbu, Aniseed Syrup, Chai |
| Their names, in a list | `["Konbu", "Aniseed Syrup", "Chai"]` |

So it returns `["Konbu", "Aniseed Syrup", "Chai"]`.

**Your job:** write the method `budgetPicks(List<Product> products, int count)` so it returns a `List<String>`: the names in the box.

- Only the products with more than 0 units in stock.
- Cheapest first.
- At most `count` names. When fewer products are in stock, all of them.
- The product names, not the products.
- When no product is in stock, or the list is empty, return an empty list.

Practiced live on the lesson page: write the Java right there and check it.

## Check yourself

2 questions to try on the lesson page.

## So what

Sorting with a comparator, paging with `skip` and `limit`, and asking yes-or-no questions turn the loops behind most list pages into one readable stream each. Next, [Counting, Collecting and Flattening Streams](https://www.ask-codey.com/lessons/common-java-stream-functions-collecting?course=java-full-stack-bootcamp) uses the same products to count, total, join and group them.

## Sources

- Oracle, [Stream (Java SE 25 & JDK 25)](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/stream/Stream.html): the API reference for `sorted`, `limit`, `skip`, `anyMatch`, `allMatch`, `noneMatch`, `findFirst` and `toList`.
- Oracle, [Comparator (Java SE 25 & JDK 25)](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Comparator.html): the API reference for `comparing`, `reversed` and `thenComparing`.
- Oracle, [Optional (Java SE 25 & JDK 25)](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/util/Optional.html): the API reference for `orElse`.

## Key terms

- [Comparator](https://www.ask-codey.com/glossary/comparator)
- [Method Reference](https://www.ask-codey.com/glossary/method-reference)
- [Optional](https://www.ask-codey.com/glossary/optional)

## Cheat sheets

- [common-java-stream-functions-cheat-sheet](https://www.ask-codey.com/cheat-sheets/common-java-stream-functions-cheat-sheet)

Source: https://www.ask-codey.com/lessons/common-java-stream-functions
