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

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...

Java Hashset HackerRank Solution | Programming Blog

Java Hashset HackerRank Solution with Explanation   Problem Statement :- In computer science, a set is an abstract data type that can store certain values, without any particular order, and no repeated values. {1,2,3} is an example of a set, but {1,2,2} is not a set. Today you will learn how to use sets in java by solving this problem. You are given n pairs of strings. Two pairs (a,b) and (c,d) are identical if a = c and b = d. That also implies (a,b) is not same as (b,a). After taking each pair as input, you need to print number of unique pairs you currently have. See full problem description in HackerRank Website :- https://www.hackerrank.com/challenges/java-hashset/problem Let's see solution of problem. import java.util.HashSet; import java.util.Scanner; public class Solution {     public static void main(String[] args) {         Scanner s = new Scanner(System.in);         System.out.println("Enter tot...