Home >Java >javaTutorial >How Can I Group Data by Multiple Fields in Java 8 Using `Collectors.groupingBy()`?

How Can I Group Data by Multiple Fields in Java 8 Using `Collectors.groupingBy()`?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-24 10:27:11713browse

How Can I Group Data by Multiple Fields in Java 8 Using `Collectors.groupingBy()`?

Grouping by Multiple Fields in Java 8, Beyond Single Field Grouping

Grouping objects by a single field is a common operation in data processing. However, scenarios may arise where grouping by multiple fields is necessary. The initial code snippet provided demonstrates grouping by the age field. This article delves into options for grouping by multiple fields from the same POJO.

Chaining Collectors

A straightforward approach is to chain multiple collectors. The code below demonstrates this technique:

Map<String, Map<Integer, List<Person>>> map = people
    .collect(Collectors.groupingBy(Person::getName,
        Collectors.groupingBy(Person::getAge));

With this approach, to retrieve a list of 18 year old individuals named Fred:

map.get("Fred").get(18);

Defining a Grouping Record

Creating a class that represents the grouping is another method. Here, a record is utilized to represent the combination of name and age:

class Person {
    record NameAge(String name, int age) {}

    public NameAge getNameAge() {
        return new NameAge(name, age);
    }
}

Then, grouping can be performed as follows:

Map<NameAge, List<Person>> map = people.collect(Collectors.groupingBy(Person::getNameAge));

To search within the grouped data:

map.get(new NameAge("Fred", 18));

Using Pair Classes from Framework Libraries

Libraries like Apache Commons provide pair classes for this type of scenario. With a pair class, the key to the map can be constructed as:

Map<Pair<String, Integer>, List<Person>> map =
    people.collect(Collectors.groupingBy(p -> Pair.of(p.getName(), p.getAge())));

To retrieve from the map:

map.get(Pair.of("Fred", 18));

Conclusion

Java 8's Collectors.groupingBy() method provides flexibility in grouping data. This article demonstrated different approaches to extend grouping beyond a single field, including chaining collectors, defining a custom grouping record, and utilizing pair classes from framework libraries. Additionally, records in Java make it easier to define grouping criteria without the need for custom classes.

The above is the detailed content of How Can I Group Data by Multiple Fields in Java 8 Using `Collectors.groupingBy()`?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn