Java Streams with Filters Examples

Java Streams with Filters tutorial

Streams is one of the most powerful feature that were added to Java core libraries in the Java 8 version. In this tutorial, we will take a look at various examples to make use of filter() with Streams and related methods to find a solution to a use-case,

Filter method signature:
Stream<T> filter(Predicate<? super T> predicate);

Example 1: Use Stream filter to find even and off numbers

In this example, we have made use of filter() with collect() method to collect result as a List.


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

public class JavaStreamFiltersExamples {

    public static void main(String[] args) {

        List<Integer> numbers = new ArrayList<>();

        List<Integer> evenNumbers = -> number %2 ==0).collect(Collectors.toList());
        List<Integer> oddNumbers = -> number %2 !=0).collect(Collectors.toList());
        System.out.println("Even Numbers" + evenNumbers);
        System.out.println("Odd Numbers" + oddNumbers);

Even Numbers[2, 4, 6, 8, 10]
Odd Numbers[1, 3, 5, 7, 9]

Example 2: Use Stream filter to all names starts with letter S

In this example, have make use of filter() with forEach() to print out the results on console,

public static void main(String[] args) {
 List<String> names = new ArrayList<>();
 names.addAll(Arrays.asList("Sam", "Chris", "Mike", "Eric", "Jose", "Samuel", "Scott"));
 System.out.println("All Names starting with Letter S in list " + names + " are: "); -> name.startsWith("S")).forEach(System.out::println);

All Names starting with Letter S in the list [Sam, Chris, Mike, Eric, Jose, Samuel, Scott] are:

Example 3: Use Stream filter to get the sum of all numbers > 3 in the list

In this example, have made use of filter() to filter out numbers > 3 and them used mapOfInt() and finally sum() to get the sum,

public static void main(String[] args) {
 List<Integer> numbers = Arrays.asList(5,2,6,8,9,1);
 int sum = -> number > 3).mapToInt(i -> i).sum();
 System.out.println("Sum of numbers > 3 is "+ sum);

Sum of numbers > 3 is 28

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail:

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap