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

Sales by Match HackerRank Solution | Java Solution

HackerRank Sales by Match problem solution in Java   Problem Description : Alex works at a clothing store. There is a large pile of socks that must be paired by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. For example, there are n=7 socks with colors socks = [1,2,1,2,1,3,2]. There is one pair of color 1 and one of color 2 . There are three odd socks left, one of each color. The number of pairs is 2 .   Example 1 : Input : n = 6 arr = [1, 2, 3, 4, 5, 6] Output : 0 Explanation : We have 6 socks with all different colors, So print 0. Example 2 : Input : n = 10 arr = [1, 2, 3, 4, 1, 4, 2, 7, 9, 9] Output : 4 Explanation : We have 10 socks. There is pair of color 1, 2, 4 and 9, So print 4. This problem easily solved by HashMap . Store all pair of socks one by one in Map and check if any pair is present in Map or not. If pair is present then increment ans variable by 1 ...

Queen's Attack II HackerRank Solution in Java with Explanation

Queen's Attack II Problem's Solution in Java (Chessboard Problem)   Problem Description : You will be given a square chess board with one queen and a number of obstacles placed on it. Determine how many squares the queen can attack.  A queen is standing on an n * n chessboard. The chess board's rows are numbered from 1 to n, going from bottom to top. Its columns are numbered from 1 to n, going from left to right. Each square is referenced by a tuple, (r, c), describing the row r and column c, where the square is located. The queen is standing at position (r_q, c_q). In a single move, queen can attack any square in any of the eight directions The queen can move: Horizontally (left, right) Vertically (up, down) Diagonally (four directions: up-left, up-right, down-left, down-right) The queen can move any number of squares in any of these directions, but it cannot move through obstacles. Input Format : n : The size of the chessboard ( n x n ). k : The number of obstacles...