Home » Java stream filter and collect

Java stream filter and collect

Java stream filter and collect

1. Overview

The Stream API introduced in Java 8 is used to process a collection of objects. It represents a sequence of objects and provides various utility methods to produce the desired result. In this article, we will learn to filter the stream in Java 8 and collect.

2. Java stream filter

One of the utility method filter() helps to filter the stream elements based on a given predicate. The predicate is a functional interface that takes a single element as an argument and evaluates it against a specified condition.

It returns a stream consisting of filtered elements. The method signature of the filter method is:

Stream<T> filter(Predicate<? super T> predicate)

3. Java stream collect

The collect is one of Java 8’s Stream API methods. It is a mutable reduction operation on the elements of this stream using a Collector. A mutable reduction operation accumulates input elements into a mutable result container, such as a Collection or StringBuilder, as it processes the elements in the stream.

Several implementations of Collector are available for use:

  1. Collectors.toSet(): Returns a Collector that accumulates the input elements into a new Set.
  2. Collectors.toMap(): To accumulate elements into a Map
  3. Collectors.toList(): To accumulate the input elements to a List

4. Java stream filter and collect as list example

For example, the following filter method filters the list of fruit names that end with the "fruit" suffix. It then collects them to a list.

List<String> fruits = Arrays.asList("mango", "grapes", "apple", "papaya", "jack fruit", "dragon fruit");
List<String> result = fruits.stream()
    .filter(name -> name.endsWith("fruit"))
    .collect(Collectors.toList());
System.out.println("Final result : " + result);

5. Java stream filter and collect as map example

For example, the following code filters the employees whose department name is "CS" and then collects them as a map. This map contains the employee id as key and employee name as value.

import java.util.*;
import java.util.stream.*;
public class MyClass {
    public static void main(String args[]) {
     List<Employee> employeeList = Arrays.asList(new Employee(101, "Joe", "CS"), 
     new Employee(102, "Kevin", "CS"), 
     new Employee(103, "Chris", "Civil"));
     Map<Integer, String> empMap = employeeList.stream()
     .filter(emp -> emp.getDeptName() == "CS").collect(Collectors.toMap(Employee::getEmpId, Employee::getEmpName));
     System.out.println(empMap);
    }
}
class Employee {
    public Employee(int empId, String empName, String deptName) {
        this.empId = empId;
        this.empName = empName;
        this.deptName = deptName;
    }
    private int empId;
    private String empName;
    private String deptName;
    public int getEmpId() {
        return this.empId;
    }
    public String getEmpName() {
        return this.empName;
    }
    public String getDeptName() {
        return this.deptName;
    }
}

If you execute the above code, it prints the following output in console:

{101=Joe, 102=Kevin}

7. Conclusion

To sum up, we have learned to filter the stream based on multiple conditions in Java 8 along with example. To explore more Java topics, see our articles.

1 thought on “Java stream filter and collect”

  1. Pingback: Java stream optional - TedBlob

Leave a Reply

Your email address will not be published.