Main Tutorials

Java 8 Streams filter examples

In this tutorial, we will show you few Java 8 examples to demonstrate the use of Streams filter(), collect(), findAny() and orElse()

1. Streams filter() and collect()

1.1 Before Java 8, filter a List like this :

BeforeJava8.java

package com.mkyong.java8;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class BeforeJava8 {

    public static void main(String[] args) {

        List<String> lines = Arrays.asList("spring", "node", "mkyong");
        List<String> result = getFilterOutput(lines, "mkyong");
        for (String temp : result) {
            System.out.println(temp);    //output : spring, node
        }

    }

    private static List<String> getFilterOutput(List<String> lines, String filter) {
        List<String> result = new ArrayList<>();
        for (String line : lines) {
            if (!"mkyong".equals(line)) { // we dont like mkyong
                result.add(line);
            }
        }
        return result;
    }

}

Output


spring
node

1.2 The equivalent example in Java 8, stream.filter() to filter a List, and collect() to convert a stream into a List.

NowJava8.java

package com.mkyong.java8;

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

public class NowJava8 {

    public static void main(String[] args) {

        List<String> lines = Arrays.asList("spring", "node", "mkyong");

        List<String> result = lines.stream()                // convert list to stream
                .filter(line -> !"mkyong".equals(line))     // we dont like mkyong
                .collect(Collectors.toList());              // collect the output and convert streams to a List

        result.forEach(System.out::println);                //output : spring, node

    }

}

Output


spring
node

2. Streams filter(), findAny() and orElse()

Person.java

package com.mkyong.java8;

public class Person {

    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    //gettersm setters, toString
}

2.1 Before Java 8, you get a Person by name like this :

BeforeJava8.java

package com.mkyong.java8;

import java.util.Arrays;
import java.util.List;

public class BeforeJava8 {

    public static void main(String[] args) {

        List<Person> persons = Arrays.asList(
                new Person("mkyong", 30),
                new Person("jack", 20),
                new Person("lawrence", 40)
        );

        Person result = getStudentByName(persons, "jack");
        System.out.println(result);

    }

    private static Person getStudentByName(List<Person> persons, String name) {

        Person result = null;
        for (Person temp : persons) {
            if (name.equals(temp.getName())) {
                result = temp;
            }
        }
        return result;
    }
}

Output


Person{name='jack', age=20}

2.2 The equivalent example in Java 8, use stream.filter() to filter a List, and .findAny().orElse (null) to return an object conditional.

NowJava8.java

package com.mkyong.java8;

import java.util.Arrays;
import java.util.List;

public class NowJava8 {

    public static void main(String[] args) {

        List<Person> persons = Arrays.asList(
                new Person("mkyong", 30),
                new Person("jack", 20),
                new Person("lawrence", 40)
        );

        Person result1 = persons.stream()                        // Convert to steam
                .filter(x -> "jack".equals(x.getName()))        // we want "jack" only
                .findAny()                                      // If 'findAny' then return found
                .orElse(null);                                  // If not found, return null

        System.out.println(result1);
        
        Person result2 = persons.stream()
                .filter(x -> "ahmook".equals(x.getName()))
                .findAny()
                .orElse(null);

        System.out.println(result2);

    }

}

Output


Person{name='jack', age=20}
null

2.3 For multiple condition.

NowJava8.java

package com.mkyong.java8;

import java.util.Arrays;
import java.util.List;

public class NowJava8 {

    public static void main(String[] args) {

        List<Person> persons = Arrays.asList(
                new Person("mkyong", 30),
                new Person("jack", 20),
                new Person("lawrence", 40)
        );

        Person result1 = persons.stream()
                .filter((p) -> "jack".equals(p.getName()) && 20 == p.getAge())
                .findAny()
                .orElse(null);

        System.out.println("result 1 :" + result1);

        //or like this
        Person result2 = persons.stream()
                .filter(p -> {
                    if ("jack".equals(p.getName()) && 20 == p.getAge()) {
                        return true;
                    }
                    return false;
                }).findAny()
                .orElse(null);

        System.out.println("result 2 :" + result2);

    }


}

Output


result 1 :Person{name='jack', age=20}
result 2 :Person{name='jack', age=20}

3. Streams filter() and map()

NowJava8.java

package com.mkyong.java8;

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

public class NowJava8 {

    public static void main(String[] args) {

        List<Person> persons = Arrays.asList(
                new Person("mkyong", 30),
                new Person("jack", 20),
                new Person("lawrence", 40)
        );

        String name = persons.stream()
                .filter(x -> "jack".equals(x.getName()))
                .map(Person::getName)                        //convert stream to String
                .findAny()
                .orElse("");

        System.out.println("name : " + name);

        List<String> collect = persons.stream()
                .map(Person::getName)
                .collect(Collectors.toList());

        collect.forEach(System.out::println);

    }
    
}

Output


name : jack

mkyong
jack
lawrence
Note
Highly recommend this Streams tutorial – Processing Data with Java SE 8 Streams

References

  1. Java 8 cyclic inference in my case
  2. Java 8 Explained: Using Filters, Maps, Streams and Foreach to apply Lambdas to Java Collections!
  3. Java 8 forEach examples
  4. Java 8 Streams: multiple filters vs. complex condition
  5. Processing Data with Java SE 8 Streams

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
31 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Aditi Patel
6 years ago

Java 8 goes one more step ahead and has developed a Streams API which lets us think about parallelism. Nowadays, because of the tremendous amount of development on the hardware front, multicore CPUs are becoming more and more general.

Great Article. Keep going !!

Can you post the basic interview questions for this topic?

I Love Programming
5 years ago

A tutorial in Java 8 that returns null. Not cool.

Sudhir
3 years ago

Nice post. Can you please add example where we can use ternary operator inside stream filter.

Maki
2 years ago
 private static List<String> getFilterOutput(List<String> lines, String filter) {
        List<String> result = new ArrayList<>();
        for (String line : lines) {
            if (!"mkyong".equals(line)) { // we dont like mkyong
                result.add(line);
            }
        }
        return result;
    }

This should be
if (!filter.equals(line)) {

Akshay
6 years ago

private static Person getStudentByName(List persons, String name) {

Person result = null;
for (Person temp : persons) {
if (name.equals(temp.getName())) {
result = temp;
}
}
return result;
}

You need to break the loop once you have found the result.

bakcsa83
6 years ago

Thanks for posting this nice example. However, everybody should know that stream().filter() 3 times slower than a good old for loop with “manual” filtering on the desired properties.

Anthonius
5 years ago
Reply to  bakcsa83

it depends on how you’re comparing it. Sequential streams? Parallel streams? Streams are NOT always slower than loops. Yes, streams are sometimes slower than loops, but they can also be equally fast; it depends on the circumstances.

TKBHL
6 years ago

These examples as useful as always here. Thanks a lot! But I’m not sure about “.orElse(null)”. Avoiding null to indicate absent of the result is the whole point of Optional, and this is re-introducing the null.

Python490
7 years ago

In your first example shouldn’t you be using !filter.equals(line)?

lounes
4 years ago
Reply to  Python490

yes i think too

Xyz
6 years ago
Reply to  Python490

List result = lines.stream()
.filter(line -> !filter.equals(line))
.collect(Collectors.toList());

Xyz
6 years ago
Reply to  Python490

Yes

Marcus Menezes
4 years ago

Great!!!! Thanks

Nilson
5 years ago

Hi, Could you check the method getFilterOutput ? you have an unused parameter

Claus
5 years ago

Hi mkyong,
Your tutorials are great. What about starting a blog on minds.com?
The times of Facebook and Twitter are coming to an end …
Regards
Claus

degan
6 years ago

Thank you
It is very useful

Rock
6 years ago

Hi,
how can i filter String only by char? i.g. i want to remove some char from a String?

Oleh
2 years ago
Reply to  Rock

Better way to manipulate with Strings is regular expressions. IMHO.

yang
6 years ago
Reply to  Rock

you can sue String.chars to get it

Random
6 years ago

Thanks a lot! This was so helpful!

Jenith
6 years ago

Hi MKYong how to compare a field from two lists of object and it should return the filtered values as list of first list type.

Rob
7 years ago

How would I filter the last (n) elements added to list using streams?

Savani
7 years ago

Love you mkyong. Great Job. Requesting you to please do the same job for spring boot and other modules like Spring Cloud etc..

Mykola Bova
7 years ago

Thanks a lot!! A question. Regarding parts Streams filter(), findAny() and orElse() What if more than one result will be found? Can we expect a List as result? Thank you!!!!

Mo
7 years ago
Reply to  Mykola Bova

A little late, but for anyone looking at this later. I believe you can convert the stream to a list using .collect(Collectors.toList()) on the stream.

Linh
2 years ago

Dear Mkyong,

Thanks for your post, it is very helpful.
i wondering that, this tutorial,
findAny() -> in the for each, the result will always find the last matched item in the list, but in the stream(). filter -> the result will do random; because the stream will not process the result as order;
I think the result will be diffence with the list includes multiple values mathe with codition in the filtering in the list.

Tushar ( Scientist Android Developer )
4 years ago

Great…….thanks 😉

Prakash Hadgal
4 years ago

Great !!!!!!

rahul
6 years ago

thanks for sharing

Malipan Bâ
6 years ago

Hello @Mkyon. Is there possible to multiple filter like this:
Person result1 = persons.stream()
.filter((p) -> “jack”.equals(p.getName())).filter((p)-> 20 == p.getAge()))
.findAny()
.orElse(null);

lounes
4 years ago
Reply to  Malipan Bâ

i think you can do this .filter(p-> {“jack”.equals(p.getName()) && 20==p.getAge()});