Skip to main content

Java 8 Stream API Filter() Method with Examples | Programming Blog

Java 8 Stream Filter with Lambda Expression

Java 8 Stream Filter method with examples
Java 8 Stream Filter() method with Examples

What is Filter in Java Stream?

    Simply, as a name suggest it filters data based on given predicate (boolean) Condition. The condition is applied to all element of Stream, and those who satisfied the condition moves to next stage and those who does not pass filtered out.

For example, If you want to filter list of Integer based on greater than some value or if you want to get even or odd data then you can easily filtered out.

Stream Filter() method is Intermediate Operation.

If you want to learn about difference between Intermediate and Terminal operation check out:-

The benefit of using filter() method is lazy evaluation. Means no data comparison is performed unless you call a terminal operation like forEach() or Collect().

We will use Lambda expression for filter elements based on given Predicate. Learn more about Lambda Expression :

Lets see how filter method works using examples.

Example 1 :- Filter Odd or Even numbers on given List

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

public class FilterDemo {

    public static void main(String[] args) {
       
        List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10);
       
        // Get Even Numbers
        System.out.println("Even Numbers");
        list.stream().filter(number -> number % 2 == 0)
            .forEach(System.out::println);

        // Get Odd Numbers
        // Filtered and collect in list
        List<Integer> filteredList = list.stream()
            .filter(number -> number % 2 != 0)
            .collect(Collectors.toList());
       
        System.out.println("Odd Numbers");
        System.out.println(filteredList);
    }

}

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


Explanation :-

  • In first filter, filtered odd numbers and print even numbers using forEach() terminal method.
  • In second filter, filtered out even data and collect odd numbers to new list using collect() Method.

Example 2 :- Filter() method on String of List

package Java8;

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

public class FilterDemo {

    public static void main(String[] args) {
       
        List<String> list = new ArrayList<>();
        list.add("Java");
        list.add("JavaScript");
        list.add("Python");
        list.add("Php");
        list.add("Angular");
        list.add("C++");
        list.add("React");
        list.add("C#");
        list.add("NodeJs");
        list.add("AI");
       
        // String greater than 4
        System.out.println("String greater than 4");
        list.stream()
            .filter(string -> string.length() > 4)
            .forEach(System.out::println);
       
        System.out.println("String Start with char J");
        list.stream()
            .filter(string -> string.startsWith("J"))
            .forEach(System.out::println);
       
    }

}

Output :-
String greater than 4
JavaScript
Python
Angular
React
NodeJs

String Start with char J
Java
JavaScript

We can apply multiple filter also on same list. Example, we can filter condition for odd or even number and also number can be greater than some number.

lets see example of applying multiple filter().

Example 3 :- Java 8 Multiple Filter() Example

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

public class FilterDemo {

    public static void main(String[] args) {
       
        List<String> list = new ArrayList<>();
        list.add("Java");
        list.add("JavaScript");
        list.add("Python");
        list.add("Php");
        list.add("Angular");
        list.add("C++");
        list.add("React");
        list.add("C#");
        list.add("NodeJs");
        list.add("AI");
       
        System.out.println("Multiple Filter : "
                + "Start with J and Length greter then 4");
        list.stream()
            .filter(string -> string.startsWith("J"))
            .filter(string -> string.length() > 4)
            .forEach(System.out::println);
           
        System.out.println("Multiple Filter : "
                + "start with C and find first filterd string");
        String filterdString = list.stream()
            .filter(string -> string.startsWith("C"))
            .findFirst().get();
       
    }

}

Output :-
Multiple Filter : Start with J and Length greter then 4
JavaScript
Multiple Filter : start with C and find first filterd string
C++

We have seen how to filter List of Integer and List of String, So lets see how to filter Data based on list of Objects.

We will create custom java class, add two fields name and salary and filtered out data by salary property. 

Example 4 :- Java 8 Filter on list of Object properties

User.java

package Java8;

public class User {
     
    private String name;
    private Integer salary;
    
    public User(String name, Integer salary) {
        this.name = name;
        this.salary = salary;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getSalary() {
        return salary;
    }
    public void setSalary(Integer salary) {
        this.salary = salary;
    }

    @Override
    public String toString() {
        return "User [name=" + name + ", salary=" + salary + "]";
    }
    
}
 

FilterDemo.java

package Java8;

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

public class FilterDemo {

    public static void main(String[] args) {
            
        List<User> list = Arrays.asList(
            new User("User 1", 10000),
            new User("User 2", 20000),
            new User("User 3", 30000),
            new User("User 4", 40000)
        );
       
        List<User> filterdUser = list.stream()
            .filter(user -> user.getSalary() > 21000)
            .collect(Collectors.toList());
       
        System.out.println(filterdUser);
       
    }
}

Output :-

[User [name=User 3, salary=30000], User [name=User 4, salary=40000]]

You can see how easily we can filter our data with Java 8 Stream filter() method. 

Conclusion :

We learned about :

  1. How to use stream filter() method based on given condition. 
  2. We use forEach() method for printing filtered elements after filter() method. 
  3. We also seen how to use collect() method for collecting filtered elements and store into another list.
  4. How to use multiple filter condition simultaneously on list.
  5. How to filter out data by custom object properties.

Happy Reading, Happy Coding.

Check out Other Java 8 Stream Methods :-

Other Articles you may like :-

Comments

Popular posts from this blog

Flipping the Matrix HackerRank Solution in Java with Explanation

Java Solution for Flipping the Matrix | Find Highest Sum of Upper-Left Quadrant of Matrix Problem Description : Sean invented a game involving a 2n * 2n matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times. The goal of the game is to maximize the sum of the elements in the n *n submatrix located in the upper-left quadrant of the matrix. Given the initial configurations for q matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix's upper-left quadrant is maximal.  Input : matrix = [[1, 2], [3, 4]] Output : 4 Input : matrix = [[112, 42, 83, 119], [56, 125, 56, 49], [15, 78, 101, 43], [62, 98, 114, 108]] Output : 119 + 114 + 56 + 125 = 414 Full Problem Description : Flipping the Matrix Problem Description   Here we can find solution using following pattern, So simply we have to find Max of same number of box like (1,1,1,1). And last

Plus Minus HackerRank Solution in Java | Programming Blog

Java Solution for HackerRank Plus Minus Problem Given an array of integers, calculate the ratios of its elements that are positive , negative , and zero . Print the decimal value of each fraction on a new line with 6 places after the decimal. Example 1 : array = [1, 1, 0, -1, -1] There are N = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.400000, 2/5 = 0.400000 and 1/5 = 0.200000. Results are printed as:  0.400000 0.400000 0.200000 proportion of positive values proportion of negative values proportion of zeros Example 2 : array = [-4, 3, -9, 0, 4, 1]  There are 3 positive numbers, 2 negative numbers, and 1 zero in array. Following is answer : 3/6 = 0.500000 2/6 = 0.333333 1/6 = 0.166667 Lets see solution Solution 1 import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static java.util.st