![]() |
VOOZH | about |
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.
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.
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
https://www.geeksforgeeks.org/
Example 2: Filter Even Numbers
4 10
Sometimes we want to filter elements based on their position in a collection.
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.
stream a of like
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.
stream a of like
We can use any Java Object property for filtering. Here we are filtering by age.
Employee [name=Kumar, age=40] Employee [name=Rakesh, age=35]
We can also create a custom function for filtering. The function must take a parameter and return a boolean value.
madam refer racecar