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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

packagejava8;

import java.util.ArrayList;

import java.util.List;

import java.util.stream.Collectors;

publicclassStudent{

Stringname;

intage;

Student(Stringname,intage){

this.name=name;

this.age=age;

}

@Override

publicStringtoString(){

returnname;

}

publicstaticvoidmain(String[]args){

//Create an list of student of objects

ArrayList stdList=newArrayList();

stdList.add(newStudent("Peter",22));

stdList.add(newStudent("Sara",23));

stdList.add(newStudent("Danial",21));

stdList.add(newStudent("Siemen",22));

//use stream operation to filter student name started with S

List filtered=

stdList

.stream()

.filter(s-&gt;s.name.startsWith("S"))

.collect(Collectors.toList());

//Print the list filtered using stream operation

System.out.println(filtered);

}

}

Output :

1

[Sara,Siemen]

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

Age Summary:IntSummaryStatistics{count=4,sum=88,min=21,average=22.000000,max=23}

Join Person by Age:Peter andDanial andSiemen are22year old orless.

Mapping keys andValues together:{21=Danial,22=Peter;Siemen,23=Sara}

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

packagejava8;

import java.util.ArrayList;

import java.util.StringJoiner;

import java.util.stream.Collector;

publicclassStudent{

Stringname;

intage;

Student(Stringname,intage){

this.name=name;

this.age=age;

}

@Override

publicStringtoString(){

returnname;

}

publicstaticvoidmain(String[]args){

// Create an list of student of objects

ArrayList stdList=newArrayList();

stdList.add(newStudent("Peter",22));

stdList.add(newStudent("Sara",23));

stdList.add(newStudent("Danial",21));

stdList.add(newStudent("Siemen",22));

Collector&lt;Student,StringJoiner,String&gt;stdNameCollector=

Collector.of(

()-&gt;newStringJoiner(", "),// supplier

(i,s)-&gt;i.add(s.name.toUpperCase()),// accumulator

(x,y)-&gt;x.merge(y),// combiner

StringJoiner::toString);// finisher

Stringnames=stdList

.stream()

.collect(stdNameCollector);

System.out.println(names);

}

}

Output

1

PETER,SARA,DANIAL,SIEMEN

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.