Home >Java >javaTutorial >How to Group Objects by Multiple Fields in Java 8 Using Collectors.groupingBy()?
Grouping Objects by Multiple Fields in Java 8
The Collectors.groupingBy() method in Java 8 is a powerful tool for organizing objects based on a single field. However, there may be scenarios where you need to group objects by multiple fields simultaneously.
To group by multiple fields, you have several options:
Chaining Collectors
You can chain multiple collectors to group by different fields in sequence. For example, to group by name and then by age, you can use the following code:
Map<String, Map<Integer, List<Person>>> map = people .collect(Collectors.groupingBy(Person::getName, Collectors.groupingBy(Person::getAge)));
Defining a Group Record
Alternatively, you can define a class that represents the grouping criteria. For instance, you could create a NameAge record that encapsulates the name and age fields:
class Person { record NameAge(String name, int age) { } public NameAge getNameAge() { return new NameAge(name, age); } }
Then, you can group by the NameAge record using:
Map<NameAge, List<Person>> map = people.collect(Collectors.groupingBy(Person::getNameAge));
Using Pair Classes
If you prefer not to implement your own group record, you can utilize pair classes provided by Java frameworks such as Apache Commons Pair. To group by name and age using Pair:
Map<Pair<String, Integer>, List<Person>> map = people.collect(Collectors.groupingBy(p -> Pair.of(p.getName(), p.getAge())));
Conclusion
Chaining collectors, defining group records, and utilizing pair classes are all viable methods for grouping objects by multiple fields in Java 8. The choice depends on your specific needs and preferences.
The above is the detailed content of How to Group Objects by Multiple Fields in Java 8 Using Collectors.groupingBy()?. For more information, please follow other related articles on the PHP Chinese website!