Stream filter in java

Introduction

In this article, we will filter elements of a stream using predicate and filtering unique elements of a stream.

Filter

The filter is an intermediate operation supported by a stream in java. It is used to filter stream data based on the predicate (predicate returns a boolean value) passed as an argument into it. For example, you can filter even numbers from a list of n natural numbers.

List numbers = Arrays.asList(1,2,3,4,5,6,7,8,9,10);

List evenNumbers = numbers.stream().filter(n->n%2==0).collect(Collectors.toList());

 Filtering a Stream of n Natural numbers

 

Filtering unique elements

Streams distinct method that returns a stream with unique elements, For example, the following code filters all even numbers from a list and makes sure that there are no duplicates.

List numbers = Arrays.asList(7,3,4,5,11,6,7,8,9,10);
List evenNumbers = numbers.stream().filter(n->n%2==0).distinct().collect(Collectors.toList());
System.out.println(evenNumbers);
Output: [2, 4, 6, 8, 10]

Summary

  1. filter() method performs an intermediate operation on stream.
  2. It takes Predicate(always returns a boolean value) as an input parameter to filter the stream data.