ZetCode

Filtering a list in Java

last modified July 4, 2024

In this article we show how to filter a list in Java.

To filter a list in Java, we either use a for loop and an if condition or we utilize the stream's filter method.

Filter a list of integers

In the first example, we filter a list of integers.

Main.java
import java.util.List;
import java.util.ArrayList;

void main() {

    var vals = List.of(-3, 0, 1, -1, 2, 5, 12, 8, -7, -2, 11);
    var res = new ArrayList<Integer>();

    for (int e: vals) {

        if (e > 0) {
            res.add(e);
        }
    }

    System.out.println(res);
}

The example filters all positive values to a new list.

for (int e: vals) {

    if (e > 0) {
        res.add(e);
    }
}

If the value satisfies the condition, it is added to the res list with add method.


The next code example uses the filter method.

Main.java
import java.util.List;

void main() {

    var vals = List.of(-3, 0, 1, -1, 2, 5, 12, 8, -7, -2, 11);
    var res = vals.stream().filter(e -> e > 0).toList();

    System.out.println(res);
}

We turn the list into a stream and apply the filter method. The condition is specified with the e -> e > 0 lambda expression.

Filter a list of words

Next we filter a list of words.

Main.java
import java.util.ArrayList;
import java.util.List;

void main() {

    var words = List.of("war", "water", "cup", "cloud",
         "spy", "sky", "terrain", "book", "forest");

    List<String> res = new ArrayList<>();

    for (var word: words) {
        if (word.startsWith("w") || word.startsWith("c")) {
            res.add(word);
        }
    }

    System.out.println(res);
}

We have a list of words. We include all words into the new list that either start with w or c.


Now we filter the words with filter method.

Main.java
import java.util.List;

void main() {

    var words = List.of("war", "water", "cup", "cloud",
            "spy", "sky", "terrain", "book", "forest");

    var res = words.stream()
            .filter(word -> word.startsWith("w") || word.startsWith("c"))
            .toList();

    System.out.println(res);
}

Filter a list of objects

In the next example we filter a list of user objects.

Main.java
import java.util.ArrayList;
import java.util.List;

void main() {

    var p1 = new User("Michael", 23, Gender.MALE);
    var p2 = new User("Jane", 24, Gender.FEMALE);
    var p3 = new User("John", 44, Gender.MALE);
    var p4 = new User("Peter", 54, Gender.MALE);
    var p5 = new User("Lucy", 35, Gender.FEMALE);

    var users = List.of(p1, p2, p3, p4, p5);
    var res = new ArrayList<User>();

    for (User user : users) {
        if (user.age() > 30) {
            res.add(user);
        }
    }

    System.out.println(res);
}

enum Gender {
    MALE, FEMALE
}

record User(String name, int age, Gender gender) {
}

The program filter out all users that are older than thirty.


The next program filters out all females.

Main.java
import java.util.List;

void main() {

    var p1 = new User("Michael", 23, Gender.MALE);
    var p2 = new User("Jane", 24, Gender.FEMALE);
    var p3 = new User("John", 44, Gender.MALE);
    var p4 = new User("Peter", 54, Gender.MALE);
    var p5 = new User("Lucy", 35, Gender.FEMALE);

    var users = List.of(p1, p2, p3, p4, p5);
    var res = users.stream().filter(u -> u.gender == Gender.FEMALE).toList();

    res.forEach(System.out::println);
}

enum Gender {
    MALE, FEMALE
}

record User(String name, int age, Gender gender) {
}

We pass the u -> u.gender == Gender.FEMALE lambda expression to filter all females from a group of users.

Filtering a list with Eclipse Collections

In the following example, we are going to filter a list with Eclipse Collections.

Eclipse Collections is a collections framework for Java. It has JDK-compatible List, Set and Map implementations with a rich API, additional types not found in the JDK like Bags, Multimaps and set of utility classes that work with any JDK compatible Collections, Arrays, Maps or Strings.

<dependencies>
    <dependency>
        <groupId>org.eclipse.collections</groupId>
        <artifactId>eclipse-collections-api</artifactId>
        <version>11.1.0</version>
    </dependency>

    <dependency>
        <groupId>org.eclipse.collections</groupId>
        <artifactId>eclipse-collections</artifactId>
        <version>11.1.0</version>
    </dependency>
</dependencies>

For the program, we use these two Maven dependencies.

Main.java
import org.eclipse.collections.api.block.predicate.Predicate;
import org.eclipse.collections.impl.factory.Lists;
import org.eclipse.collections.impl.utility.Iterate;

import java.util.List;


void main() {

    var persons = Lists.immutable.of(

            new User("Michael", 34, Gender.MALE),
            new User("Jane", 17, Gender.FEMALE),
            new User("John", 28, Gender.MALE),
            new User("Peter", 47, Gender.MALE),
            new User("Lucy", 27, Gender.FEMALE)
    );

    Predicate<User> lessThan30 = person -> person.age() < 30;
    List<User> res = (List<User>) Iterate.select(persons, lessThan30);
    System.out.println(res);
}


enum Gender {
    MALE,
    FEMALE
}

record User(String name, int age, Gender gender) {
}

The code example creates a filtered list containing persons younger than thirty.

Predicate<User> lessThan30 = person -> person.age() < 30;

A predicate is created to accept elements whose age is lower than thirty.

List<User> res = (List<User>) Iterate.select(persons, lessThan30);

The Iterate.select returns a new collection with only the elements that evaluated to true for the specified predicate.

Source

Java ArrayList - language reference

In this article we have showed how to filter a list in Java.

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all Java tutorials.