Stream Filter() In Java With Examples

March 28, 2022
Stream filter



Introduction

A stream is a very unique offering in Java.  It is a sequence of objects that supports various methods that are applicable in various algorithms in Java. Introduced back in Java 8, the Stream API is used to process steams as a collection of objects. It is to be noted that a stream cannot be considered as a data structure as it itself takes the data input from Collections, Arrays or I/O channels. In this article, we will be focusing on the java stream filter, one of the most useful methods of the stream, and how it can be applied with some other stream methods in Java.

Java stream filter()

The stream filter() in Java is an intermediate operation that takes the data input from a stream and returns a transformed stream based on the provided condition.

 

The Java stream filter() method syntax is as follows:

Stream<T> filter(Predicate<? super T> condition)

The Predicate mentioned here is a functional interface that represents the condition to filter out the elements from the Stream that does not fulfill the condition.

The returned Stream then only contains the specific elements from the given stream that matched the provided predicate. The Predicate is a functional interface that is why a lambda expression can also be passed in it.

To get started, see this basic example below . Here, a stream is created using the stream() method that consists of a list of names.

 

After that, another stream is created that will contain only long names filtered out from the first string:

1.  import java.util.Arrays;
2.  import java.util.List;
3.  import java.util.stream.Stream;
4.  public class filterLongNames {
5.     public static void main(String[] args) {
6.	 
7.   List<String> names = Arrays.asList("Alexander","James","John","Dave","Jefferson");
8.			
9.   //Creating a stream of myNames
10.	    Stream<String> myNames = names.stream();
11.			
12.	    //Creating a new stream consisting of long names
13.	   Stream<String> longNames = myNames.filter(str -> str.length() >= 6);
14.			
15.	   //output the long names
16.	   longNames.forEach(str->System.out.print(str+", "));
17.     }
18.   }

Output:

Alexander, Jefferson,

Java Stream filter() Operations

Following are some crucial operations along with their examples which can be used with the Java streams filter() method.

– Stream filter() with collect() method

The collect(Collectors.toList()) method can be used with the Java streams filter() to collect the Stream of filtered elements into a List.

This example is just a different approach for the code in the previous example.

 

Here, we are collecting the long names directly into a List rather than creating another stream:

1. import java.util.Arrays;
2. import java.util.List;
3. import java.util.stream.Collectors;
4. public class Main 
5. {
6.    public static void main(String[] args) 
7.    {
8.  List<String> names = Arrays.asList("Alexander","James","John","Dave","Jefferson");
9.  List<String> longNames = names.stream().filter(str -> str.length() >= 
    6).collect(Collectors.toList());
10.   System.out.println(longNames);
11.     }
12. }

Output:

[Alexander, Jefferson]

– Java Stream filter() with map()

The Java Streams filter() method can be used with the map() method to collect the elements from a stream and then each element can be finally collected into a list after transformation.

Now, extending the previous example, the long names will be capitalized in the map and then will be collected in a list.

 

See the demonstration below where the same example is shown but this time with map():

1. import java.util.Arrays;
2. import java.util.List;
3. import java.util.stream.Collectors;
4. public class Main 
5. {
6.     public static void main(String[] args) 
7.      {
        List<String> names = Arrays.asList("Alexander", "James", "John", "Dave", 
"Jefferson", “Steve”, “Cameron”);
8.     List<String> longNames = names.stream().filter(str -> str.length() >= 
    6).map(str.toUpperCase()).collect(Collectors.toList()); 
9.     System.out.println(longNames);
10.    }
11. }
12. 

Output:

[ALEXANDER, JEFFERSON, CAMERON]

– Using multiple conditions in Predicate

In all the previous examples, we have seen that there is only one condition applied in the Java streams filter() method but more than one condition can also be used in the filter() method.

You can join multiple conditions to further filter out the elements using the logical operators in java.

 

In the following example, two conditions are used with the filter method and they are joined together using and (&&) logical operator:

1. import java.util.Arrays;
2. import java.util.List;
3. import java.util.stream.Collectors;
4. 
5.   public class Example {
6. 
7.     public static void main(String[] args) {
8. 
9.         List<String> myNames = Arrays.asList("Alexander", "James", "John", "Dave",
       "Jefferson", “Steve”, “Cameron”);
10.           List<String> longnames = myNames.stream() 
11.                 .filter(str -> str.length() > 3 && str.length() < 5)
12.                 .collect(Collectors.toList()); 
13.            longnames.forEach(System.out::println); 
14. 
15.     }
16. 
17. }

Output:

John
Dave

– Java stream filter() with Lambda Expression

In the example below, a lambda expression is used as a predicate. A stream consisting of integers is iterated and all the positive numbers from the Stream will be printed.

 

The inline predicate ‘num -> num > 0‘used in the following code is a lambda expression:

1. import java.util.Arrays;
2. import java.util.List;
3. 
4. public class Main 
5.  {
6.      public static void main(String[] args) 
7.      {
8.           List<Integer> list = Arrays.asList(-25, 27, 3, -43, 51, -67, 47, -8,
              -32, 10);
9. 
10.       list.stream().filter(n -> n > 0).forEach(System.out::println);
11.      }
12. }

Output:

27
3
51
10

– Java Stream Filter() with a custom predicate

This example is performing the same function as the previous example, it outputs the positive numbers from a list but here the Predicate class is used instead of the lambda expression.

 

You can write any condition inside the predicate that matches your requirement:

1.  import java.util.Arrays;
2.  import java.util.List;
3.  import java.util.function.Predicate;
4. 
5.  public class Main 
6. {
7.     public static void main(String[] args) 
8.     {
9.         List<Integer> list = Arrays.asList(-25, 27, 3, -43, 51, -67, 
            47, -8, -32, 10);
10. 
11.        Predicate<Integer> myCondition = new Predicate<Integer>() 
12.        {
13.        @Override
14.        public boolean test(Integer num) {
15.            if (num > 0) {
16.              return true;
17.        }
18.        return false;
19.      }
20.    };
21. 
22.    list.stream().filter(condition).forEach(System.out::println);
23.    }
24. }

Output:

27
3
51
10

– Using Java Stream filter() with objects

 

The Java streams filter() method can also be used to filter out objects in a stream:

1. public class Student {
2. 
3. private String name;
4. private String ID;
5. 
6. public Student(String name, String ID) {
7. this.name = name;
8. this.ID = ID;
9. }
10. 
11. public String getName() {
12. return name;
13. }
14. 
15. public void setName(String name) {
16. this.name = name;
17. }
18. 
19. public String getID() {
20. return email;
21. }
22. 
23. public void setID(String ID) {
24. this.ID = ID;
25. }
26. }
27.

 

In the below example, this basic Student class with two attributes will be utilized.

1.   import java.util.Arrays;
2.   import java.util.List;
3.   import java.util.stream.Collectors;
4. 
5. public class FilteringObjects {
6. 
7.    public static void main(String[] args) {
8. 
9.       List<Student> user = Arrays.asList(
10.          new Student("Michael", "CS1212"),
11.          new Student("Sam", "ME1763"),
12.          new Student("Sara", "CS1984"),
13.          new Student("Ron", "BS0392"),
14.          new Student("Mark", "ME0321")
15.    );
16. 
17.    List<Student> result = users.stream()
18.          .filter(user -> user.getID().matches("CS.*"))
19.          .collect(Collectors.toList());
20. 
21.       result.forEach(u -> System.out.println(u.getName()));
22.    }
23. }

The example creates a stream of Student objects and filters out those students whose ID match the “CS.*” regular pattern (Starts with ‘CS’).

Output 

Michael

Sara

– Exception handling with Java stream Filter()

The methods used in the predicates usually consist of simple comparisons and do not end up throwing any Exceptions but in certain cases, methods that could throw an exception could be used in the Predicate.

To cater to that, the try-catch statement is used to catch the checked exception.

After that, it gives you a choice to either handle the exception or rethrow it as an unchecked exception.

 

The example given below, demonstrate an example of handling checked exception thrown from a method used in the predicate:

1. List<String> longNames = list.stream()
2.     .filter(x -> {
3.            try {
4.               return x.CheckedException();
5.         } catch (IOException e) {
6.              throw new UncheckedException(e);
7.         }
8.    })
9.    .collect(Collectors.toList());

Conclusion

We have discussed various types of combinations with the Java stream filter()  that can be used to filter out certain elements from the list, objects and stream depending on the condition(s) provided.

Also Read: Java Compiler Error: “class, interface, or enum expected”

It can also be combined with Java streams, array lists, collections, and many others based on the requirements of the program.



author

shaharyar-lalani

Shaharyar Lalani is a developer with a strong interest in business analysis, project management, and UX design. He writes and teaches extensively on themes current in the world of web and app development, especially in Java technology.


Candidate signup

Create a free profile and find your next great opportunity.

JOIN NOW

Employer signup

Sign up and find a perfect match for your team.

HIRE NOW

How it works

Xperti vets skilled professionals with its unique talent-matching process.

LET’S EXPLORE

Join our community

Connect and engage with technology enthusiasts.

CONNECT WITH US