Advance Streams Operations

Plethora of different operations available with streams. Some basic and very important operations are already been discussed in previous article (read it from here). Let’s see how collect, flatMap and reduce operations works.

How to use Collect operation in streams?

Collect is used to transform the elements of the stream into a different data structures such as List, Set and Map. Collect accepts a collector which is based on operations like supplier, accumulator, combiner and finisher. The following example shows how to construct a list from stream elements and prints the result on the console.

Output :

Another example used to group student  and construct a list from streams elements, averaging the student age and displaying. In another example, a more comprehensive statistics is been returned by a summarizing collector containing min, max, total number of students, sum on age and average age  of student. Further example is using join the student who met a specific condition and using delimiter to separate each student.

Output

Another more complicated example is to build your own special collector. In the example below we transformed the stream into a single String containing all names in upper letter and separated by comma delimiter. We used all four ingredients such as supplier, accumulator, combiner and finisher.

Output

How to use FlatMap Operations?

FlatMap returns a stream which consist of the results, came from replacing each element of current stream with another mapped stream.  Map has a limitation that can map exactly one other object. FlatMap can be used to overcome this kind of shortcomings and one object is transformable to multiple others.

In below example we are using two classes Student and Register. We used stream to instantiate Student and Register objects in the main method of the program. The we created three classes for every single student.

Output

How reduce works in stream?

The reduction operation combines all elements of the stream into a single result.

Output

The following method accepts both identity value and a BinaryOperator accumulator and aggregate names and ages of all student in stream.

Output

Comments

  1. Reply

Leave a Reply

Your email address will not be published. Required fields are marked *