Java 11: Understanding Stream Operations
In Java, Stream operations can be classified into two categories: intermediate operations and terminal operations. Below is a list of some of the most common Stream operations in Java 11, along with a brief description of each.
Intermediate Operations
- filter(Predicate
predicate): Filters the Stream's elements based on the given predicate and returns a new Stream containing only the elements that meet the predicate's condition. - map(Function
mapper): Applies the given mapping function to each element of the Stream and returns a new Stream with the resulting elements. - flatMap(Function
> mapper): Applies the given mapping function to each element of the Stream and "flattens" the result into a new Stream. Useful for combining multiple Streams into a single one. - distinct(): Returns a new Stream containing only distinct elements based on their natural equality comparison.
- sorted(): Returns a new Stream containing the elements sorted according to their natural order.
- sorted(Comparator
comparator): Returns a new Stream containing the elements sorted according to the provided comparator. - peek(Consumer
action): Performs an action on each element of the Stream as they pass by, typically used for debugging or performing side effects. Returns a new Stream containing the same elements.
Terminal Operations
- forEach(Consumer
action): Performs an action for each element of the Stream. Does not return any result. - toArray(): Converts the Stream into an array containing all its elements.
- reduce(BinaryOperator
accumulator): Iteratively applies an accumulator function to the Stream's elements, and returns an Optional with the accumulated result. - collect(Collector
collector): Performs a mutable reduction on the Stream's elements using a Collector, and returns the result. - min(Comparator
comparator): Finds and returns the minimum element of the Stream according to the provided comparator. - max(Comparator
comparator): Finds and returns the maximum element of the Stream according to the provided comparator. - count(): Counts the number of elements in the Stream and returns the result.
- anyMatch(Predicate
predicate): Checks if any element of the Stream meets the condition of the given predicate. - allMatch(Predicate
predicate): Checks if all elements of the Stream meet the condition of the given predicate.