0

Group List items into Several Lists using Stream in Java 8

Group List items into Several Lists using Stream in Java 8 is easy.

We have a list of Persons and we want to group them into Female, Male, Unknown list using Stream and Collectors in Java 8.

PersonBean

Below is a simple class that represents a person. It has a name and gender fields. The toString() method has been overriden to display its fields’ contents in human-readable form.

Main Class

Below is the main class that uses Stream, and Collectors.

Output

myMap will have 3 lists for each gender – male, female, and unknown.

Useful links

http://www.oracle.com/technetwork/articles/java/ma14-java-se-8-streams-2177646.html

https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html

Karl San Gabriel

Karl San Gabriel

Java and Enterprise Technologies Expert