Grouping by Multiple Fields in Java 8
Grouping objects by multiple field names is a common operation in Java programming, and it can be easily achieved using Java 8's Stream API and the Collectors.groupingBy() method.
The code provided in the question demonstrates how to group objects by a single field name:
Map<Integer, List<Person>> peopleByAge = people .collect(Collectors.groupingBy(p -> p.age, Collectors.mapping((Person p) -> p, toList())));
To group objects by multiple fields, the first option is to chain multiple collectors:
Map<String, Map<Integer, List<Person>>> map = people .collect(Collectors.groupingBy(Person::getName, Collectors.groupingBy(Person::getAge)));
Another option is to create a class that represents the grouping criteria, such as NameAge in the following code:
class Person { record NameAge(String name, int age) { } public NameAge getNameAge() { return new NameAge(name, age); } } ... Map<NameAge, List<Person>> map = people.collect(Collectors.groupingBy(Person::getNameAge));
Finally, it's possible to use a third-party library such as Apache Commons Pair to create a Pair object for grouping:
Map<Pair<String, Integer>, List<Person>> map = people.collect(Collectors.groupingBy(p -> Pair.of(p.getName(), p.getAge())));
By leveraging these grouping techniques, it's possible to efficiently group objects by multiple field names in Java 8, providing a convenient way to organize and access data based on specific criteria.
The above is the detailed content of How Can I Group Objects by Multiple Fields Using Java 8 Streams?. For more information, please follow other related articles on the PHP Chinese website!