Collecting the elements of a stream

Java streams allow you to process a sequence of elements in a sequential or parallel way. You can create a stream from different data sources, as a Collection, a File or an Array and apply to its elements a sequence of operations normally defined with lambda expressions. Those operations can be divided into two different classes:

  • Intermediate operations: These operations return other Stream as a result and allow you to filter, transform, or sort the elements of the stream
  • Terminal operations: These operations return a result after processing the elements of the stream

A stream has a source, zero or more intermediate operations, and a terminal operation. The two most important terminal operations are:

  • The reduce operation, which allows you to obtain a unique result after processing the elements of the stream. This result usually is a summary of the processed data. The Reducing the elements of a stream recipe explains you how to use reduce operations in Java.
  • The collect operation that allows you to generate a data structure with the results of processing the elements of the stream. This is also called a mutable reduction operation as the result is a mutable data structure.

In this recipe, we will learn how to execute collect operations in Java streams with the different versions of the collect() method and the auxiliary Collectors class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.244.228