In this tutorial, we will see “How to use Streams to Filter a List in Java 8?”. We are going to use how Java 8 Streams API can be used to filter an ArrayList. Java 8 streams filter example

Check out: ArrayList ListIterator in Java with Examples

Java 8 Streams Filter Example...!!! Share on X

Filter List using ‘Java 8 Streams’

/** 
 * Filter a List using Java8 Streams 
 * @author Deepak Verma 
 */

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Filter_List_Using_Java8_Streams {

    public static void main(String[] args) {

        List<Actor> listOfActors = getActors();
        
        var filteredResult = listOfActors.stream()
        		                         .filter(person -> person.getAge() > 45)
                                         .collect(Collectors.toList());

        System.out.println("Filtered Result:\n"+filteredResult.toString());
        
    }

    static List <Actor> getActors() {

        List <Actor> actors = new ArrayList <Actor> ();

        actors.add(new Actor(5, "yashu"));
        actors.add(new Actor(64, "gaurangee"));
        actors.add(new Actor(93, "isha"));
        actors.add(new Actor(8, "deepak"));
        actors.add(new Actor(87, "yashi"));

        return actors;

    }

}


class Actor {

    int age;
    String name;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }


    public Actor(int age, String name) {
        this.name = name;
        this.age = age;
    }
    
    @Override
    public String toString() {

        final StringBuilder sb = new StringBuilder("Actor{");

        sb.append("name=").append(name);
        sb.append(", age=").append(age);
        sb.append('}');

        return sb.toString();
    }

}

Output:

Filtered Result:
[Actor{name=gaurangee, age=64}, Actor{name=isha, age=93}, Actor{name=yashi, age=87}]

Java 8 streams filter example

Java 8 Streams Filter Example...!!! Share on X

Do you like this Post? – then check my other helpful posts:

Other Useful References:

Filter Java ArrayList

Filter Java ArrayList

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester.

    He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    View all posts