Java Stream collect() operation with examples
20 total views, 1 views today
Welcome to Java 8 series. In this tutorial, you will learn about java stream collect() operation with examples.
Stream collect() is a reduction operation performed on the stream of elements. It applies a certain function on the stream of elements to generate the final output.
Stream collect() is mainly used for,
- converting the stream of elements into a collection interface such as List, Set or Map.
- Collect the elements from the stream and store it in the collection.
- Perform count, min, max, and sum.
- Perform aggregate operations such as GroupBy
- Concatenate the elements of the stream into a single result using Joining.
All the above Stream collect operations are provided via an API called Collectors.
The Collectors API has all required operations that are supported by Stream collect() operation.
<R> R collect(Supplier<R> supplier,BiConsumer<R,? super T> accumulator,BiConsumer<R,R> combiner)
<R,A> R collect(Collector<? super T,A,R> collector)
Let us see detailed examples of Stream collect() operation.
- Accumulate Stream of elements in a list
- Accumulate Stream of elements in a Set
- Accumulate Stream of elements in a Map
- Convert a Stream to HashMap
- Convert a Stream to LinkedHashMap
- Collectors averagingDouble()/averagingInt/averagingLong
References :Official documentation
Check out this link to learn more about Java 8 features and stream operations
I hope you like this article. Thanks for reading and Please leave us a comment below!