Java Stream filter With Examples

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

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.

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

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.

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.

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.

Above program produces below output.

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

That’s all for java stream filter examples.

Reference: Java 8 Official Documentation on Stream Filter

By admin

Leave a Reply