Java Stream Filter is a useful method in the Streams API that allows you to select elements based on a condition.
In this chapter, you will learn about the Java Stream filter() method, its usage, benefits, and how it works with stream operations.
The Streams API provides a new abstraction to work with sequences of data. It allows developers to perform operations on collections (like Lists, Sets, and Maps) in a declarative manner, leveraging functional programming concepts.
Streams support various operations, categorized into intermediate and terminal operations. Intermediate operations return a stream, allowing method chaining, while terminal operations produce a result or a side-effect, terminating the stream pipeline.
The filter() method is an intermediate operation that takes a Predicate (a functional interface) as an argument. A Predicate is a functional interface with a single abstract method, test(), which returns a boolean value. The filter() method processes each element of the stream and includes it in the result only if the predicate evaluates to true.
The signature of Stream filter() method is given below:
predicate: It takes a Predicate reference as an argument. Since Predicate is a functional interface, we can also pass a lambda expression.
It returns a new stream.
Let's understand how the filter() method works in Streams with different examples.
In this example, filtered data is fetched and iterated using the filter() method.
In the following example, we are fetching and iterating filtered data.
Output:
90000.0
In this example, filtered data is collected into a list using the filter() method.
Output:
[90000.0]
We request you to subscribe our newsletter for upcoming updates.