00:00

Filter and Sort a List Using Java Streams

Last updated:

Filtering and sorting a list is the most common job for Java streams (Java 8+): take a List, keep the elements that match some conditions with filter(), put them in order with sorted() and a Comparator, and collect the result with toList().

This page solves realistic variants of that task with complete programs: filtering by several conditions, multi-field and reverse sorting, nulls, dynamic filters chosen at run time, and paging the result. Each pattern links to the detailed tutorial for the method it uses.

1. The Filter and Sort Recipe

The basic recipe
List<Product> result = products.stream()
        .filter(p -> p.category().equals("Audio"))              // 1. keep what matches
        .filter(p -> p.price() <= 5_000)
        .sorted(Comparator.comparing(Product::rating).reversed()  // 2. order the rest
                .thenComparing(Product::price))
        .skip(0).limit(10)                                        // 3. optional paging
        .toList();                                                // 4. collect

filter() takes a Predicate, sorted() takes a Comparator, and toList() (Java 16) returns an unmodifiable list. On Java 8 to 15, use collect(Collectors.toList()).

2. How the Pipeline Works

The stream reads the list, drops non-matching elements one at a time, and passes the survivors to sorted(), which buffers and sorts them. Because sorting costs more than filtering, the order filter, then sort is both correct and efficient. The original list is never changed.

Filter, sort, page, collect A list of products is filtered by category and price, sorted by rating descending then price, limited to a page of results and collected into a list. Filtering before sorting means fewer elements are sorted. products.stream() SOURCE filterrules sortedrating, price skip, limitone page toList()result page RESULT FILTER, SORT, PAGE
Figure 1: Filter first so the sort handles only the matching elements; page last.

3. Real-World Examples

Example 1: Several conditions and a multi-field sort (Java 16+)

An online store shows in-stock audio products under Rs 5,000, best rated first and, for equal ratings, cheapest first.

ProductSearch.java
import java.util.Comparator;
import java.util.List;

public class ProductSearch {

    record Product(String name, String category, int price, double rating, boolean inStock) { }

    public static void main(String[] args) {
        List<Product> catalogue = List.of(
                new Product("Earbuds Lite", "Audio", 1_499, 4.2, true),
                new Product("Studio Monitor", "Audio", 18_999, 4.8, true),
                new Product("Bass Speaker", "Audio", 3_999, 4.5, true),
                new Product("Neckband", "Audio", 1_299, 4.5, true),
                new Product("Smart Watch", "Wearables", 4_499, 4.1, true),
                new Product("Soundbar Mini", "Audio", 4_799, 4.6, false));

        List<String> results = catalogue.stream()
                .filter(p -> p.category().equals("Audio"))
                .filter(Product::inStock)
                .filter(p -> p.price() <= 5_000)
                .sorted(Comparator.comparingDouble(Product::rating).reversed()
                        .thenComparingInt(Product::price))
                .map(p -> p.name() + " (" + p.rating() + ", Rs " + p.price() + ")")
                .toList();

        results.forEach(System.out::println);
    }
}
Output
Neckband (4.5, Rs 1299)
Bass Speaker (4.5, Rs 3999)
Earbuds Lite (4.2, Rs 1499)

How it works: Three filters express three business rules. The comparator sorts by rating descending and breaks the tie between the two 4.5-rated products by price.

Example 2: Filters chosen at run time (Java 16+)

A search API receives optional criteria. Only the criteria that are present should be applied.

DynamicFilters.java
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.function.Predicate;

public class DynamicFilters {

    record Flat(String city, int bedrooms, int rent) { }

    static List<Flat> search(List<Flat> flats, String city, Integer minBedrooms, Integer maxRent) {
        List<Predicate<Flat>> rules = new ArrayList<>();
        if (city != null) rules.add(f -> f.city().equalsIgnoreCase(city));
        if (minBedrooms != null) rules.add(f -> f.bedrooms() >= minBedrooms);
        if (maxRent != null) rules.add(f -> f.rent() <= maxRent);

        Predicate<Flat> all = rules.stream().reduce(f -> true, Predicate::and);

        return flats.stream()
                .filter(all)
                .sorted(Comparator.comparingInt(Flat::rent))
                .toList();
    }

    public static void main(String[] args) {
        List<Flat> flats = List.of(new Flat("Pune", 2, 22_000), new Flat("Pune", 3, 31_000),
                new Flat("Mysuru", 2, 15_000), new Flat("Pune", 1, 14_000));

        System.out.println(search(flats, "pune", 2, null));
        System.out.println(search(flats, null, null, 20_000));
    }
}
Output
[Flat[city=Pune, bedrooms=2, rent=22000], Flat[city=Pune, bedrooms=3, rent=31000]]
[Flat[city=Pune, bedrooms=1, rent=14000], Flat[city=Mysuru, bedrooms=2, rent=15000]]

How it works: Each present criterion becomes a Predicate. reduce(f -> true, Predicate::and) combines them into one, starting from a predicate that accepts everything, so a search with no criteria returns all flats.

Example 3: Sorting with missing values (Java 16+)

Sort employees by joining date, newest first, with employees whose date is unknown at the end, then by name.

SortWithMissingDates.java
import java.time.LocalDate;
import java.util.Comparator;
import java.util.List;

public class SortWithMissingDates {

    record Employee(String name, LocalDate joined) { }

    public static void main(String[] args) {
        List<Employee> staff = List.of(
                new Employee("Rehan", LocalDate.of(2023, 4, 1)), new Employee("Asha", null),
                new Employee("Mitali", LocalDate.of(2025, 1, 15)), new Employee("Bilal", null));

        staff.stream()
                .sorted(Comparator.comparing(Employee::joined, Comparator.nullsLast(Comparator.<LocalDate>reverseOrder()))
                        .thenComparing(Employee::name))
                .forEach(e -> System.out.println(e.name() + " " + e.joined()));
    }
}
Output
Mitali 2025-01-15
Rehan 2023-04-01
Asha null
Bilal null

How it works: nullsLast(reverseOrder()) sorts real dates newest first and puts the unknown ones last; thenComparing(Employee::name) orders those alphabetically.

Example 4: One page of sorted results (Java 16+)

Return page 2 (pages of 3) of tickets ordered by priority and age, with the total count for the page header.

PagedTickets.java
import java.util.Comparator;
import java.util.List;
import java.util.stream.IntStream;

public class PagedTickets {

    record Ticket(int id, int priority, int ageHours) { }

    public static void main(String[] args) {
        List<Ticket> tickets = IntStream.rangeClosed(1, 8)
                .mapToObj(i -> new Ticket(i, i % 3 + 1, i * 5))
                .toList();

        Comparator<Ticket> order = Comparator.comparingInt(Ticket::priority)
                .thenComparing(Comparator.comparingInt(Ticket::ageHours).reversed());

        int page = 2, size = 3;
        List<Integer> pageIds = tickets.stream()
                .sorted(order)
                .skip((long) (page - 1) * size)
                .limit(size)
                .map(Ticket::id)
                .toList();

        System.out.println("Showing page " + page + " of " + (tickets.size() + size - 1) / size + ": " + pageIds);
    }
}
Output
Showing page 2 of 3: [4, 1, 8]

How it works: Sorting happens before paging, so every page shows a consistent slice of the same order. skip() and limit() select the page; for database-backed data, page in the query instead.

4. Real-World Use Cases

  • E-commerce: product search with filters and sort options.
  • HR and CRM: employee or customer lists filtered by status and sorted by date.
  • Support desks: ticket queues ordered by priority and age.
  • Admin screens: any table with filter boxes and sortable columns over in-memory data.

5. Important Points

  • Filter before sort for efficiency.
  • Stable sort: equal elements keep their original order, so add tie-breakers for predictable results.
  • Nulls need nullsFirst()/nullsLast() in comparators and null checks in predicates.
  • The source list is unchanged; use list.sort() or removeIf() to change it in place.
  • Large data should be filtered and sorted in the database.

6. Stream vs Other Approaches

ApproachChanges the list?Best for
Stream: filter().sorted().toList()NoDerived views, API responses
list.removeIf(p) + list.sort(c)YesUpdating a mutable list in place
SQL WHERE + ORDER BY-Large tables
Loop with manual sortDependsRarely needed

Method details: filter(), sorted(), skip() and limit().

7. Common Mistakes and Best Practices

Sorting before filtering

Slower
products.stream().sorted(byRating).filter(Product::inStock).toList();   // sorts items that are then dropped

Reversing the whole comparator chain

A trailing .reversed() reverses every key. Reverse only the key that needs it, for example thenComparing(Ticket::ageHours, Comparator.reverseOrder()).

Other mistakes to avoid

  • Modifying the result of toList(). It is unmodifiable.
  • Paging before sorting, which gives inconsistent pages.
  • Comparators that subtract values, which can overflow.

8. Summary

  • Filter with predicates, sort with comparators, collect with toList().
  • Filter before sorting; page after sorting.
  • Combine optional criteria into one predicate with Predicate::and.
  • Handle nulls with nullsFirst()/nullsLast() and add tie-breakers.

9. References