Home > Java > javaTutorial > How Can I Group Objects by Multiple Fields Using Java 8 Streams?

How Can I Group Objects by Multiple Fields Using Java 8 Streams?

Patricia Arquette
Release: 2024-12-04 00:11:10
Original
642 people have browsed it

How Can I Group Objects by Multiple Fields Using Java 8 Streams?

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())));
Copy after login

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)));
Copy after login

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));
Copy after login

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())));
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template