VOOZH about

URL: https://www.geeksforgeeks.org/java/java-stream-api-filters/

⇱ Java Stream API – Filters - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Java Stream API – Filters

Last Updated : 25 Oct, 2025

The Stream Filter API is used to process elements in a stream based on a Predicate. A predicate is a functional interface that takes an argument of any type and returns a Boolean.

  • If the predicate returns true, the element is passed to the next operation in the stream pipeline.
  • If false, the element is filtered out.

Syntax

stream.filter(predicate)

We can filter a stream in different ways depending on our needs or the type of data. Let's discuss them one by one.

1. Filtering by Simple Object Properties

Filter by Object properties uses java operators. The below example explains how to filter by properties of an object.

Example 1: Filter Strings Starting with a Prefix


Output
https://www.geeksforgeeks.org/

Example 2: Filter Even Numbers


Output
4
10

2. Filtering by Index

Sometimes we want to filter elements based on their position in a collection.

Approach 1: Using AtomicInteger

We need to use AtomicInteger because predicates expect final variables as parameters. As long as filter function(Predicate) returns boolean we can use any expression. Here, getAndIncrement() method of AtomicInteger increments the current value by 1 and returns final int value.


Output
stream
a
of
like

Approach 2: Using IntStream

We can use Intstream and map the array elements based on the index. Here first we create an Intstream of a range of numbers. Check if a number is even, then overwrite/map the integer with the array element.


Output
stream
a
of
like

3. Filtering by Custom Object Properties

We can use any Java Object property for filtering. Here we are filtering by age.


Output
Employee [name=Kumar, age=40]
Employee [name=Rakesh, age=35]

4. Custom Filter Functions

We can also create a custom function for filtering. The function must take a parameter and return a boolean value.


Output
madam
refer
racecar
Comment
Article Tags:
Article Tags: