Java Stream filter

Filed Under: Java

Java Stream filter can be very helpful when you want to do some processing only on some elements of the Stream based on certain condition.

Java Stream filter

java stream filter
Stream was introduced in Java 8. Java Stream filter is an intermediate operation, i.e. it returns a new Stream.

Java Stream filter example

Let’s look at a simple example to count the even numbers in a list of integers. We can do it like below.


List<Integer> intList = generateList(); //some method to create the list of integers
int evenCount = 0;
for(int i : intList){
	if(i%2==0){
		evenCount++;
		//code to do some processing
	}
}
System.out.println("Even Number Count: "+evenCount);

Now let’s see how we can do the same thing using java stream filter api.


Predicate<Integer> predicate = new Predicate<Integer>(){

	@Override
	public boolean test(Integer i) {
		return (i%2==0);
	}
	
};
List<Integer> evenList = intList.parallelStream().filter(predicate).collect(Collectors.toList());
evenCount = evenList.size();
System.out.println("Even Number Count: "+evenCount);

Predicate is a functional interface that takes one argument and return boolean based on the test function. Above code can also be written as below using lambda expression.


evenCount = intList.parallelStream().filter(i -> {
	return (i % 2 == 0);
}).collect(Collectors.toList()).size();

Java Stream Filter Example 2

Let’s look at another example where we want to filter a list of integers and keep only numbers greater than 90.


List<Integer> intList = new ArrayList<>();
for(int i=50; i<100; i++) intList.add(i);

Stream<Integer> sequentialStream = myList.stream(); // we can create parallel stream too

Stream<Integer> highNumsStream = sequentialStream.filter(p -> p > 90); //filter numbers greater than 90
System.out.print("High Nums greater than 90=");
highNumsStream.forEach(p -> System.out.print(p+" "));
//prints "High Nums greater than 90=91 92 93 94 95 96 97 98 99 "

Java Stream filter Example with Objects

Let’s say we have list of employees and we want to print names of all employees with age greater than 32. Below is a simple program to do this using java stream filter.


package com.journaldev.examples;

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

public class StreamFilterExample {

	public static void main(String[] args) {
		List<Employee> empList = new ArrayList<>();
		empList.add(new Employee("Pankaj", 35));
		empList.add(new Employee("David", 25));
		empList.add(new Employee("Lisa", 31));
		empList.add(new Employee("Dean", 40));

		// print all employees above 32 years of age
		empList.stream().filter(p -> (p.getAge() > 32)).forEach(p -> System.out.println(p.getName()));

	}

}

class Employee {
	private String name;
	private int age;

	public Employee() {
	}

	public Employee(String n, int a) {
		this.name = n;
		this.age = a;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
}

Above program produces below output.


Pankaj
Dean

If we want to get the first employee only with age over 32, then we can use filter with findFirst method as shown below.


Optional<Employee> empO = empList.stream().filter(p -> (p.getAge() > 32)).findFirst();

if(empO.isPresent())
	System.out.println(empO.get().getName()+","+empO.get().getAge());

That’s all for java stream filter examples.

Reference: Java 8 Official Documentation on Stream Filter

Comments

  1. Rishi Chopra says:

    empList.stream().filter(p -> (p.getAge() > 32)).forEach(p -> System.out.println(p.getName()));

    This can be expressed more cleanly as below too.
    empList.stream().filter(p -> (p.getAge() > 32)).map(e->e.getName()).forEach(System.out::println);

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages