Java 17 Map Grouping By Example

Let’s see how to use map grouping by functionality with Java stream. We have GenericRecord class that hold the data of the person and also the addresses of the people. In many cases we want to split this information to Peron and Addresses and we want to remove the duplicate information. See how several time we have the same name for different addresses. In this cases one person have more then one address.

So this mean that from the list of GenericRecord we want to create a map with key Peron and value List of the Person’s addresses.

To to that we use Collectors.groupingBy method:

package org.example;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {

    record GenericRecord(long personId, String name, String addressTown, String addressCountry) {
    }

    record Peron(long personId, String name) {
    }

    record Address(String addressTown, String addressCountry) {
    }

    public static void main(String[] args) {
        List<GenericRecord> genericRecordList = List.of(
                new GenericRecord(1, "Clarke House", "Michigan", "US"),
                new GenericRecord(1, "Clarke House", "Texas", "US"),
                new GenericRecord(1, "Hunt Marshall", "London", "UK"),
                new GenericRecord(1, "Hunt Marshall", "London", "US"),
                new GenericRecord(1, "Harrison Brady", "Frankfurt", "DE")
        );

        Map<Peron, List<Address>> mapGroupByPerson = genericRecordList.stream()
                .collect(Collectors.groupingBy(
                        gr -> new Peron(gr.personId(), gr.name()),
                        Collectors.mapping(gr -> new Address(gr.addressTown(), gr.addressCountry()),
                                Collectors.toList())
                ));

        mapGroupByPerson.forEach((k, v) -> {
            System.out.println(k);
            System.out.println(v);
            System.out.println();
        });
    }
}

Result:

Peron[personId=1, name=Hunt Marshall]
[Address[addressTown=London, addressCountry=UK], Address[addressTown=London, addressCountry=US]]

Peron[personId=1, name=Clarke House]
[Address[addressTown=Michigan, addressCountry=US], Address[addressTown=Texas, addressCountry=US]]

Peron[personId=1, name=Harrison Brady]
[Address[addressTown=Frankfurt, addressCountry=DE]]

Leave a Comment

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.