Grouping Items with Java 8 Streams

Grouping Items with Java 8 Streams

This small example demonstrates the usage of Collectors.groupingBy to group a list of Persons by their age. The mapped result is a map of list with all Persons of the same age.

public class Person {

    private Integer age;
    private String name;

    public Person(Integer age, String name) {
        this.age = age; = name;

    public Integer getAge() {
        return age;

    public String getName() {
        return name;

    public String toString() {
        return "Person{age=" + age + ", name='" + name + "\'}";

Now group them with Collectors.groupingBy :

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;

import static;
import static;

public class Grouping {

    private static final Logger logger = LoggerFactory.getLogger(Grouping.class);

    public static void main(String[] args) {

        List<Person> people = Arrays.asList(new Person(22, "Alice"),
                new Person(45, "Bob"),
                new Person(22, "Cindy"),
                new Person(4, "Deborah"));

        Map<Integer, List<Person>> grouped =
                        mapping(Function.identity(), toList())));"grouped: {}", grouped);


grouped: {
  4=[Person{age=4, name='Deborah'}], 
  22=[Person{age=22, name='Alice'}, Person{age=22, name='Cindy'}], 
  45=[Person{age=45, name='Bob'}]