Which method is used to filter elements of a stream?
Answer:
Explanation:
The filter()
method is used to filter elements of a stream based on a given predicate. A predicate is a functional interface that takes an element as input and returns a boolean value, indicating whether the element should be included in the filtered stream. The filter()
method creates a new stream that contains only the elements that satisfy the predicate. This is particularly useful when you want to extract a subset of elements from a collection based on specific conditions.
Filtering is a common operation in data processing, where it is often necessary to select a subset of elements from a larger collection based on certain criteria. For example, you might use filter()
to select all even numbers from a list of integers, or to filter out null values from a list of strings. The filter()
method allows you to express these operations in a concise and declarative manner, improving the readability and maintainability of your code.
The filter()
method is an intermediate operation, meaning that it does not trigger the execution of the stream pipeline by itself. Instead, it creates a new stream that can be further processed by other stream operations. The final result is only produced when a terminal operation, such as collect()
or forEach()
, is invoked. This design allows for efficient and flexible data processing in Java applications.