Java 8 introduced a host of new features, with the Streams API being one of the most significant additions. Among its various functionalities, the filter() method stands out as a powerful tool for processing collections in a functional style. In this section, we will discuss the filter() method, exploring its usage, benefits, and practical applications.
The Streams API provides a new abstraction to work with sequences of data in Java. 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 Predicate reference as an argument. Predicate is a functional interface. So, we can also pass lambda expression here.
It returns a new stream.
In the following example, we are fetching and iterating filtered data.
Output:
90000.0
In the following example, we are fetching filtered data as a list.
Output:
[90000.0]
The filter() method in Java 8 Streams API is a versatile tool for processing collections. It allows developers to write concise, readable, and efficient code by leveraging functional programming concepts. Whether we are filtering primitive data types, strings, or custom objects, filter provides a straightforward approach to streamline your data processing tasks. As we delve deeper into the Streams API, we will discover even more powerful operations that can transform how we work with data in Java.
We request you to subscribe our newsletter for upcoming updates.