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 Loop, stream and removeIf Splitting, reusing conditions, nulls and duplicates Duplicates by a property How fast is each approach? Filtering by type, by position in a run, and in one step Traps: laziness, fixed-size lists and stateful filters Which approach to use
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
. The original list is untouched, which is safe when other code still uses it, and it works on immutable lists.stream().filter(...) - Change the list in place with
, removing the elements that fail. No second list is created, but the list must be mutable and everyone holding a reference sees the change.removeIf
Streams are lazy: filtertoList()limitfindFirst
| Approach | Since | Result | Best for |
|---|---|---|---|
forif | Java 1.2 | New list | Complex logic per element |
stream().filter(p).toList() | Java 8 (toList | New unmodifiable list | Most filtering, pipelines |
collect(Collectors.toList()) | Java 8 | New mutable list (in practice) | When the result will be changed |
list.removeIf(p) | Java 8 | Same list, changed | Mutable lists you own |
Collectors.partitioningBy(p) | Java 8 | Two lists: pass and fail | Needing both halves |
Predicate.andornegatePredicate.not | Java 8, Java 11 | A combined condition | Reusable rules |
All four programs were compiled and run with JDK 21. To find a single element instead, see
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.
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:
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
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.filter changed the list itself, while the originalremoveIf list was left as it was because the program filtered a copy.books (Java 16) returns an unmodifiable list. If the result will be changed afterwards, collect withstream().toList() orCollectors.toList() instead.new ArrayList<>(...)
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.
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:
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]
returns a map with keyspartitioningBy andtrue , so one pass gives both the hot and the mild days. Filtering twice with opposite conditions would scan the list twice.false- A
is an object, so a rule likePredicate can be named, tested and combined:warm keeps warm days that are not extreme.warm.and(extreme.negate()) , from Java 11, reads better thanPredicate.not(warm) with method references.warm.negate() removes nulls, andfilter(Objects::nonNull) removes duplicates usingdistinct() , keeping the first of each in order.equals
Duplicates by a property
distinct()
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:
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
of keys seen so far makes a stateful filter:HashSet isseen.add(email) only the first time. Both Dee entries survived, becausetrue andDEE@x.io are different strings. This trick is only safe in sequential streams.dee@x.io - Putting users into a
by lowercased email keeps the last user per address, in first-seen order, and treats the two Dee addresses as one.LinkedHashMap with a merge function can keep whichever duplicate a rule prefers, here the oldest user per email.toMap- 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 Integerlimit
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):
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
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.removeIf followed byfilter stopped after finding ten matches, about 30 elements into the list, and took microseconds.limit(10)
Filtering by type, by position in a run, and in one step
Plain filter
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);
}
}
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]]
followed byfilter(Circle.class::isInstance) returned amap(Circle.class::cast) with the two circles. A filter alone would still give aList<Circle> , and each later use would need its own cast.List<Shape> (Java 16) did the type test, the cast and the radius test in one lambda, using anmapMulti pattern. It passes zero or one element to the sink for each input, and kept only the circle of radius 3.instanceof- On the readings
,[3, 5, 8, 2, 9, 1] kept all four small values, whilefilter(n < 6) (Java 9) kepttakeWhile and stopped at 8.[3, 5] 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.dropWhile (Java 9) turned aStream.ofNullable value into an empty stream, so the count was 0. It saves annull when a method returns a single value that may be missing.if- Filtering a list of lists tests whole inner lists: the two orders containing
survived intact. To filter the items inside them, flatten first, as shown on theinkflatMap 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.
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);
}
}
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
ran, so building the pipeline did no work at all. Once it ran, each element went throughtoList and, if it passed, straight on tofilter , givingmap rather than four filters and then two maps.filter 1, filter 2, map 2 returns a fixed-size list. ItsArrays.asList returnedremoveIf when nothing matched and threwfalse only when it had something to remove, so tests with data that never matches will not catch the bug.UnsupportedOperationException- A list from
threw onList.of even though nothing matched. Immutable lists reject every mutator call up front.removeIf - The same condition,
, keptn > 3 with[4, 5, 6] andfilter with[1, 2, 3] . One names what stays and the other what goes, so converting between them needsremoveIf ornegate() .Predicate.not - Removing duplicates with
and a plainfilter(seen::add) 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. ParallelHashSet counted all 100,000 values correctly. A filter's predicate should not change shared state; if it must, use a concurrent set fromdistinct() .ConcurrentHashMap.newKeySet()
Which approach to use
| Situation | Use |
|---|---|
| Need a new list, original unchanged | stream().filter(p).toList() |
| New list that will be modified | collect(Collectors.toList()) |
| Change the list you own | list.removeIf(p.negate()) |
| Both matching and non-matching elements | partitioningBy(p) |
| A rule used in several places | A named Predicateandornot |
| Remove nulls | filter(Objects::nonNull) |
| Remove duplicates | distinct() |
| Only the first few matches | filter(p).limit(n) |
| Logic too complex for a lambda | A for |
Removing elements during a loop is covered on