Java 8 streams collectors groupBy

package com.bawi.java8.groupBy;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class MyJavaGroupBy {
    static class Person {
        private final String name;
        private final int age;
        public Person(String name, int age) {
   = name;
            this.age = age;
        public String getName() {
            return name;
        public int getAge() {
            return age;
        public String toString() {
            return "Person [name=" + name + ", age=" + age + "]";
    public static void main(String[] args) {
        List<Person> persons = Arrays.asList(
                new Person("John", 20), 
                new Person("Rob", 20), 
                new Person("Bartek", 22), 
                new Person("Ania", 21));
        // Group by person age, default collect to map: key=age, value = list of people (aggregate function is returning as list of persons)
        Map<Integer, List<Person>> peopleListByAge =;
        // {20=[Person [name=John, age=20], Person [name=Rob, age=20]], 21=[Person [name=Ania, age=21]], 22=[Person [name=Bartek, age=22]]}

        // Group by person age (key), map person to person name and collect the names to set (value), (aggregate function is returning as set of names)  
        Map<Integer, Set<String>> peopleNameSetByAge =, Collectors.mapping(Person::getName, Collectors.toSet())));
        // {20=[Rob, John], 21=[Ania], 22=[Bartek]}

        // Group by person age (key) and count of person for a given age (value), apply counting aggregate function  
        Map<Integer, Long> peopleByAgeWithCount =, Collectors.counting()));
        // {20=2, 21=1, 22=1}



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s