Java 8 introduced powerful filtering operations through the Stream API, enabling functional-style data processing. Filtering is used to select elements from a collection based on a condition, making code concise and readable.
Important Concepts
- Stream API: A stream is a sequence of elements that supports functional-style operations. It allows processing collections (e.g., lists, sets) in a declarative way.
- Filtering: The filter() method is used to select elements that satisfy a given predicate (a condition returning true or false).
- Predicate: A functional interface (java.util.function.Predicate) that defines the condition for filtering. It has a test() method returning a boolean.
- Intermediate and Terminal Operations:
- filter() is an intermediate operation (returns a new stream).
- A terminal operation (e.g., collect(), forEach()) is needed to produce a result or side-effect.
stream.filter(predicate).terminalOperation();
stream: The source stream (e.g., from a list: list.stream()).
predicate: A condition (e.g., x -> x > 5).
terminalOperation: Collects or processes the filtered results (e.g., collect(Collectors.toList())).
Code language: CSS (css)
Common Filtering Operations
- filter(): Selects elements matching a predicate.
- Chaining Filters: Multiple filter() calls can be chained for complex conditions.
- Combining Predicates: Use logical operators (&&, ||, !) or Predicate methods (and(), or(), negate()) to combine conditions.
Common Use Cases
- Filtering data from collections (e.g., lists, sets).
- Data validation (e.g., removing invalid entries).
- Query-like operations on objects (e.g., selecting users by criteria).