How To Filter List Using Java Stream API?

Stream API feature was introduced in Java 8 but it is still confusing for many and also many have not even used it a single time. I will try to explain Java Stream concepts with simple examples in Learn Stream API in Java with Examples series.

In this post, we will learn to filter a Java List using Stream APIs i.e. filter() method.

If you want to learn from a video tutorial then please refer to the below video –

We may be required to filter a Java List based on one or multiple conditions. We need to iterate the array and apply filter conditions. Let’s write a very simple program to filter a list.

package solveproblemswithsreams; import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors; public class FilterListUsingJavaStreamAPI { public static void main(String[] args) { List allSubjets = Arrays.asList("Java","Functional Testing", "Performace Testing", "Selenium Testing", "Mongo DB"); List allTestingSubjects = new ArrayList(); // Iterating the list for(String ele : allSubjets) { // filter condition if(ele.contains("Testing")) allTestingSubjects.add(ele); } System.out.println("All subjects : "+ allSubjets); System.out.println("All testing subjects : "+ allTestingSubjects); } }

All subjects : [Java, Functional Testing, Performace Testing, Selenium Testing, Mongo DB]
All testing subjects : [Functional Testing, Performace Testing, Selenium Testing]

Stream interface provides a method filter() which helps you to filter a list based on condition/s. The filter() method takes a Predicate which is a functional interface. We can use the lambda expressions to write shorter code.

  1. Get a sequential stream of List using stream() method.
  2. Call filter() method with the condition on stream.
  3. Collect results into a List.
package solveproblemswithsreams; import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors; public class FilterListUsingJavaStreamAPI { public static void main(String[] args) { List allSubjets = Arrays.asList("Java","Functional Testing", "Performace Testing", "Selenium Testing", "Mongo DB"); List allTestingSubjects = new ArrayList(); allTestingSubjects = allSubjets .stream() .filter(ele -> ele.contains("Testing")) .collect(Collectors.toList()); System.out.println("All subjects : "+ allSubjets); System.out.println("All testing subjects : "+ allTestingSubjects); }
}

All subjects : [Java, Functional Testing, Performace Testing, Selenium Testing, Mongo DB]
All testing subjects : [Functional Testing, Performace Testing, Selenium Testing]

You can use multiple conditions as below –

.filter(ele -> ele.contains(“Testing”) && ele.contains(“Selenium”))

https://github.com/amod-mahajan/MSE_LearnJavaStreamsWithExamples.git

If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe to my YouTube channel.
#ThanksForReading
#HappyLearning