Filter a List

Filtering keeps the elements of a list that meet a condition. Java can do it by building a new list with a loop or a stream, or by removing the rest in place with removeIf. This page explains the difference, chains and reuses conditions, splits a list in two, removes duplicates by a property, and measures the approaches.

Contents

Two ways to filter: a new list, or in place

A filter is a condition, a predicate, that says for each element whether to keep it. There are two fundamentally different ways to apply it:

  • Build a new list with the elements that pass, using a loop or stream().filter(...). The original list is untouched, which is safe when other code still uses it, and it works on immutable lists.
  • Change the list in place with removeIf, removing the elements that fail. No second list is created, but the list must be mutable and everyone holding a reference sees the change.

Streams are lazy: filter does nothing until a terminal operation such as toList() pulls elements through, and combined with limit or findFirst the stream stops as soon as it has enough.

Ways to filter a list
ApproachSinceResultBest for
for loop with ifJava 1.2New listComplex logic per element
stream().filter(p).toList()Java 8 (toList Java 16)New unmodifiable listMost filtering, pipelines
collect(Collectors.toList())Java 8New mutable list (in practice)When the result will be changed
list.removeIf(p)Java 8Same list, changedMutable lists you own
Collectors.partitioningBy(p)Java 8Two lists: pass and failNeeding both halves
Predicate.and, or, negate, Predicate.notJava 8, Java 11A combined conditionReusable rules

All four programs were compiled and run with JDK 21. To find a single element instead, see finding an element in a list.

Loop, stream and removeIf

A small list of books with prices and years is filtered by price, by a range of years, and in place, so the three approaches can be compared on the same data.

Java
import java.util.ArrayList;
import java.util.List;

public class FilterWays {

    record Book(String title, int year, double price) {
    }

    public static void main(String[] args) {
        List<Book> books = List.of(
                new Book("Dune", 1965, 9.99),
                new Book("Neuromancer", 1984, 14.50),
                new Book("Hyperion", 1989, 12.00),
                new Book("Foundation", 1951, 8.25));

        // 1. A loop into a new list
        List<Book> cheapLoop = new ArrayList<>();
        for (Book b : books) {
            if (b.price() < 10) {
                cheapLoop.add(b);
            }
        }
        System.out.println("loop:          " + titles(cheapLoop));

        // 2. Stream filter: the original list is untouched
        List<Book> cheap = books.stream().filter(b -> b.price() < 10).toList();
        System.out.println("stream filter: " + titles(cheap));

        // 3. Several conditions, then only the field you need
        List<String> eightiesTitles = books.stream()
                .filter(b -> b.year() >= 1980)
                .filter(b -> b.year() < 1990)
                .map(Book::title)
                .toList();
        System.out.println("1980s titles:  " + eightiesTitles);

        // 4. removeIf: filter a mutable list in place
        List<Book> shelf = new ArrayList<>(books);
        shelf.removeIf(b -> b.year() < 1960);
        System.out.println("removeIf:      " + titles(shelf));
        System.out.println("original:      " + titles(books));
    }

    static List<String> titles(List<Book> list) {
        return list.stream().map(Book::title).toList();
    }
}

Output:

Output
loop:          [Dune, Foundation]
stream filter: [Dune, Foundation]
1980s titles:  [Neuromancer, Hyperion]
removeIf:      [Dune, Neuromancer, Hyperion]
original:      [Dune, Neuromancer, Hyperion, Foundation]
  • The loop and the stream produced the same list of cheap books. The stream says only what to keep; the loop also spells out how to build the result.
  • Two filter calls in a row act as a logical AND, here selecting the 1980s. Each element passes through both before the next element starts, so this is not two passes over the list.
  • removeIf changed the list itself, while the original books list was left as it was because the program filtered a copy.
  • stream().toList() (Java 16) returns an unmodifiable list. If the result will be changed afterwards, collect with Collectors.toList() or new ArrayList<>(...) instead.

Splitting, reusing conditions, nulls and duplicates

Daily temperatures are split into hot and mild days, then filtered with named, combined conditions, and two small lists show null and duplicate removal.

Java
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class PartitionAndReuse {

    public static void main(String[] args) {
        List<Integer> temps = List.of(18, 31, 24, 35, 12, 29);

        // Both halves in one pass: true -> matched, false -> did not
        Map<Boolean, List<Integer>> hot = temps.stream()
                .collect(Collectors.partitioningBy(t -> t >= 28));
        System.out.println("hot days:  " + hot.get(true));
        System.out.println("mild days: " + hot.get(false));

        // Named, reusable conditions combined with and / or / negate
        Predicate<Integer> warm = t -> t >= 20;
        Predicate<Integer> extreme = t -> t >= 33 || t <= 12;
        System.out.println("warm, not extreme: "
                + temps.stream().filter(warm.and(extreme.negate())).toList());
        System.out.println("not warm:          "
                + temps.stream().filter(Predicate.not(warm)).toList());

        // Dropping nulls
        List<String> raw = Arrays.asList("a", null, "b", null);
        System.out.println("non-null:          "
                + raw.stream().filter(Objects::nonNull).toList());

        // Distinct values, keeping first-seen order
        List<Integer> repeats = List.of(3, 1, 3, 2, 1);
        System.out.println("distinct:          " + repeats.stream().distinct().toList());
    }
}

Output:

Output
hot days:  [31, 35, 29]
mild days: [18, 24, 12]
warm, not extreme: [31, 24, 29]
not warm:          [18, 12]
non-null:          [a, b]
distinct:          [3, 1, 2]
  • partitioningBy returns a map with keys true and false, so one pass gives both the hot and the mild days. Filtering twice with opposite conditions would scan the list twice.
  • A Predicate is an object, so a rule like warm can be named, tested and combined: warm.and(extreme.negate()) keeps warm days that are not extreme. Predicate.not(warm), from Java 11, reads better than warm.negate() with method references.
  • filter(Objects::nonNull) removes nulls, and distinct() removes duplicates using equals, keeping the first of each in order.

Duplicates by a property

distinct() compares whole elements, but often two elements count as duplicates when one property matches, such as users with the same email. The user list repeats one email exactly and another with different case.

Java
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public class DistinctByKey {

    record User(String name, String email, int age) {
    }

    public static void main(String[] args) {
        List<User> users = List.of(new User("Ann", "ann@x.io", 31), new User("Bob", "bob@x.io", 17),
            new User("Ann B.", "ann@x.io", 32), new User("Cy", "cy@x.io", 45),
            new User("Dee", "DEE@x.io", 29), new User("Dee", "dee@x.io", 29));

        // Keep the first user per email: a Set remembers the keys seen so far
        Set<String> seen = new HashSet<>();
        List<String> firstPerEmail = users.stream().filter(u -> seen.add(u.email()))
            .map(User::name).toList();
        System.out.println("first per email:      " + firstPerEmail);

        // Case-insensitive key, keeping the last one, with a map
        Map<String, User> lastPerEmail = new LinkedHashMap<>();
        users.forEach(u -> lastPerEmail.put(u.email().toLowerCase(), u));
        System.out.println("last per email (ci):  " + lastPerEmail.values().stream()
            .map(User::name).toList());

        // toMap with a merge function: keep the oldest user per email
        Map<String, User> oldest = users.stream().collect(Collectors.toMap(User::email, u -> u,
            (a, b) -> a.age() >= b.age() ? a : b, LinkedHashMap::new));
        System.out.println("oldest per email:     " + oldest.values().stream()
            .map(u -> u.name() + "(" + u.age() + ")").toList());

        // Filter with the index: keep every second element
        List<String> names = users.stream().map(User::name).toList();
        List<String> everySecond = new ArrayList<>();
        for (int i = 0; i < names.size(); i += 2) {
            everySecond.add(names.get(i));
        }
        System.out.println("every second:         " + everySecond);
    }
}

Output:

Output
first per email:      [Ann, Bob, Cy, Dee, Dee]
last per email (ci):  [Ann B., Bob, Cy, Dee]
oldest per email:     [Ann B.(32), Bob(17), Cy(45), Dee(29), Dee(29)]
every second:         [Ann, Ann B., Dee]
  • A HashSet of keys seen so far makes a stateful filter: seen.add(email) is true only the first time. Both Dee entries survived, because DEE@x.io and dee@x.io are different strings. This trick is only safe in sequential streams.
  • Putting users into a LinkedHashMap by lowercased email keeps the last user per address, in first-seen order, and treats the two Dee addresses as one.
  • toMap with a merge function can keep whichever duplicate a rule prefers, here the oldest user per email.
  • Filtering by position is easiest with an index loop; streams do not expose the index.

How fast is each approach?

The program keeps the multiples of 3 from two million Integers with each approach, then shows what limit does to a lazy stream. Each time is the fastest of three runs.

Java
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

public class FilterSpeed {

    public static void main(String[] args) {
        List<Integer> data = new ArrayList<>();
        for (int i = 0; i < 2000000; i++) {
            data.add(i);
        }
        System.out.printf("keep multiples of 3 from %,d Integers%n", data.size());
        time("for loop into ArrayList", data, d -> {
            List<Integer> out = new ArrayList<>();
            for (int x : d) {
                if (x % 3 == 0) {
                    out.add(x);
                }
            }
            return out;
        });
        time("stream filter toList", data, d -> d.stream().filter(x -> x % 3 == 0).toList());
        time("parallel stream", data, d -> d.parallelStream().filter(x -> x % 3 == 0).toList());
        time("copy + removeIf", data, d -> {
            List<Integer> out = new ArrayList<>(d);
            out.removeIf(x -> x % 3 != 0);
            return out;
        });
        time("filter + limit(10)", data, d -> d.stream().filter(x -> x % 3 == 0).limit(10)
            .toList());
    }

    // Best of 3 runs
    static void time(String name, List<Integer> d, Function<List<Integer>, List<Integer>> f) {
        long best = Long.MAX_VALUE;
        int size = 0;
        for (int run = 0; run < 3; run++) {
            long t0 = System.nanoTime();
            size = f.apply(d).size();
            best = Math.min(best, System.nanoTime() - t0);
        }
        System.out.printf("  %-26s %7.2f ms  (%,d kept)%n", name, best / 1e6, size);
    }
}

Output (2 CPUs, Linux, JDK 21; treat the numbers as approximate):

Output
keep multiples of 3 from 2,000,000 Integers
  for loop into ArrayList      14.63 ms  (666,667 kept)
  stream filter toList         11.67 ms  (666,667 kept)
  parallel stream               9.91 ms  (666,667 kept)
  copy + removeIf              13.76 ms  (666,667 kept)
  filter + limit(10)            0.02 ms  (10 kept)
  • The loop, the sequential stream and the parallel stream finished within a few milliseconds of each other, and their order changed between runs. Choose between the loop and the stream for readability.
  • The parallel stream gains little on two CPUs, because the per-element work is tiny and the partial results must be merged. Parallel streams help when each element needs real computation.
  • Copying the list and then calling removeIf copies all two million elements before removing two thirds of them, so it does more work than filtering into a new list, even though its time landed among the others here because copying an array of references is fast. removeIf pays off when you want to change the existing list anyway.
  • filter followed by limit(10) stopped after finding ten matches, about 30 elements into the list, and took microseconds.

Filtering by type, by position in a run, and in one step

Plain filter keeps elements that pass a test and leaves their type alone. Several related operations cover what it cannot do: narrowing a list to one subtype, stopping at the first failure, and filtering while transforming. The program applies each to a small list.

Java
import java.util.List;
import java.util.stream.Stream;

public class FilterVariants {

    sealed interface Shape permits Circle, Square {
    }

    record Circle(double r) implements Shape {
    }

    record Square(double side) implements Shape {
    }

    public static void main(String[] args) {
        List<Shape> shapes = List.of(new Circle(1), new Square(2), new Circle(3), new Square(1));

        // Keep one subtype and get a typed list back
        List<Circle> circles = shapes.stream()
            .filter(Circle.class::isInstance)
            .map(Circle.class::cast)
            .toList();
        System.out.println("filter + cast:    " + circles);

        // Java 16 mapMulti: filter and cast in one step, with a pattern match
        List<Circle> big = shapes.stream()
            .<Circle>mapMulti((s, sink) -> {
                if (s instanceof Circle c && c.r() > 2) {
                    sink.accept(c);
                }
            })
            .toList();
        System.out.println("mapMulti:         " + big);

        // Java 9 takeWhile and dropWhile stop at the first failure; filter does not
        List<Integer> readings = List.of(3, 5, 8, 2, 9, 1);
        System.out.println("filter(< 6):      " + readings.stream().filter(n -> n < 6).toList());
        System.out.println("takeWhile(< 6):   " + readings.stream().takeWhile(n -> n < 6).toList());
        System.out.println("dropWhile(< 6):   " + readings.stream().dropWhile(n -> n < 6).toList());

        // Java 9 Stream.ofNullable drops a null single value
        String maybe = null;
        System.out.println("ofNullable(null): " + Stream.ofNullable(maybe).count() + " elements");

        // Filtering a list of lists: keep inner lists that contain a match
        List<List<String>> orders = List.of(List.of("pen", "ink"), List.of("cup"),
            List.of("ink", "pad"));
        List<List<String>> withInk = orders.stream().filter(o -> o.contains("ink")).toList();
        System.out.println("orders with ink:  " + withInk);
    }
}
Output
filter + cast:    [Circle[r=1.0], Circle[r=3.0]]
mapMulti:         [Circle[r=3.0]]
filter(< 6):      [3, 5, 2, 1]
takeWhile(< 6):   [3, 5]
dropWhile(< 6):   [8, 2, 9, 1]
ofNullable(null): 0 elements
orders with ink:  [[pen, ink], [ink, pad]]
  • filter(Circle.class::isInstance) followed by map(Circle.class::cast) returned a List<Circle> with the two circles. A filter alone would still give a List<Shape>, and each later use would need its own cast.
  • mapMulti (Java 16) did the type test, the cast and the radius test in one lambda, using an instanceof pattern. It passes zero or one element to the sink for each input, and kept only the circle of radius 3.
  • On the readings [3, 5, 8, 2, 9, 1], filter(n < 6) kept all four small values, while takeWhile (Java 9) kept [3, 5] and stopped at 8. dropWhile returned the rest from 8 on, including 2 and 1. Use these two only on data that is ordered by the condition, such as a sorted list or a log read from the start.
  • Stream.ofNullable (Java 9) turned a null value into an empty stream, so the count was 0. It saves an if when a method returns a single value that may be missing.
  • Filtering a list of lists tests whole inner lists: the two orders containing ink survived intact. To filter the items inside them, flatten first, as shown on the flatMap page.

Traps: laziness, fixed-size lists and stateful filters

Filtering code is short, which makes its mistakes easy to miss. Each part of this program shows a behaviour that surprises people the first time they meet it.

Java
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class FilterTraps {

    public static void main(String[] args) {
        // 1. Nothing runs until a terminal operation, and elements go through one at a time
        List<String> log = new ArrayList<>();
        Stream<Integer> pending = Stream.of(1, 2, 3, 4)
            .filter(n -> {
                log.add("filter " + n);
                return n % 2 == 0;
            })
            .map(n -> {
                log.add("map " + n);
                return n * 10;
            });
        System.out.println("before toList: " + log);
        System.out.println("result " + pending.toList() + ", log " + log);

        // 2. removeIf on a fixed-size list fails only when something matches
        List<String> fixed = Arrays.asList("a", "b", "c");
        System.out.println("asList.removeIf(no match): " + fixed.removeIf(s -> s.equals("z")));
        try {
            fixed.removeIf(s -> s.equals("b"));
        } catch (UnsupportedOperationException e) {
            System.out.println("asList.removeIf(match): UnsupportedOperationException");
        }
        try {
            List.of("a", "b").removeIf(s -> s.equals("z"));
        } catch (UnsupportedOperationException e) {
            System.out.println("List.of.removeIf(no match): UnsupportedOperationException anyway");
        }

        // 3. removeIf keeps what fails the test: the condition is the opposite of filter's
        List<Integer> nums = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6));
        List<Integer> kept = nums.stream().filter(n -> n > 3).toList();
        nums.removeIf(n -> n > 3);
        System.out.println("filter(n > 3) keeps " + kept + ", removeIf(n > 3) keeps " + nums);

        // 4. A stateful filter in a parallel stream: HashSet is not thread-safe
        int wrongRuns = 0;
        for (int run = 0; run < 20; run++) {
            Set<Integer> seen = new HashSet<>();
            long unique = 0;
            try {
                unique = IntStream.range(0, 400000).map(i -> i % 100000).boxed().parallel()
                    .filter(seen::add).count();
            } catch (RuntimeException e) {
                unique = -1;
            }
            if (unique != 100000) {
                wrongRuns++;
            }
        }
        long viaDistinct = IntStream.range(0, 400000).map(i -> i % 100000).boxed().parallel()
            .distinct().count();
        System.out.println("parallel filter(seen::add) with a HashSet: wrong in " + wrongRuns
            + " of 20 runs; parallel distinct() counted " + viaDistinct);
    }
}
Output
before toList: []
result [20, 40], log [filter 1, filter 2, map 2, filter 3, filter 4, map 4]
asList.removeIf(no match): false
asList.removeIf(match): UnsupportedOperationException
List.of.removeIf(no match): UnsupportedOperationException anyway
filter(n > 3) keeps [4, 5, 6], removeIf(n > 3) keeps [1, 2, 3]
parallel filter(seen::add) with a HashSet: wrong in 17 of 20 runs; parallel distinct() counted 100000
  • The log was empty before toList ran, so building the pipeline did no work at all. Once it ran, each element went through filter and, if it passed, straight on to map, giving filter 1, filter 2, map 2 rather than four filters and then two maps.
  • Arrays.asList returns a fixed-size list. Its removeIf returned false when nothing matched and threw UnsupportedOperationException only when it had something to remove, so tests with data that never matches will not catch the bug.
  • A list from List.of threw on removeIf even though nothing matched. Immutable lists reject every mutator call up front.
  • The same condition, n > 3, kept [4, 5, 6] with filter and [1, 2, 3] with removeIf. One names what stays and the other what goes, so converting between them needs negate() or Predicate.not.
  • Removing duplicates with filter(seen::add) and a plain HashSet on a parallel stream gave a wrong count in most of the 20 runs, and the number of bad runs changed from build to build. Parallel distinct() counted all 100,000 values correctly. A filter's predicate should not change shared state; if it must, use a concurrent set from ConcurrentHashMap.newKeySet().

Which approach to use

Choosing a filter approach
SituationUse
Need a new list, original unchangedstream().filter(p).toList()
New list that will be modifiedcollect(Collectors.toList()) or a loop
Change the list you ownlist.removeIf(p.negate())
Both matching and non-matching elementspartitioningBy(p)
A rule used in several placesA named Predicate, combined with and, or, not
Remove nullsfilter(Objects::nonNull)
Remove duplicatesdistinct(), or a key set for duplicates by property
Only the first few matchesfilter(p).limit(n)
Logic too complex for a lambdaA for loop

Removing elements during a loop is covered on removing while iterating, and other stream operations on the streams page.