In Java 8 and later, you can use the Collectors.groupingBy
method of the Collectors
class to group the elements of a Collection
by one or more properties.
To group a Collection
by two properties, you can use the Collectors.groupingBy
method in combination with the Collectors.mapping
method, which allows you to specify a function that maps the elements of the Collection
to a new value that is used for grouping.
Here is an example of how you can use the Collectors.groupingBy
and Collectors.mapping
methods to group a List
of Person
objects by their name and age:
import java.util.List; import java.util.Arrays; import java.util.Map; import java.util.stream.Collectors; public class MyClass { public static void main(String[] args) { List<Person> people = Arrays.asList( new Person("Alice", 25), new Person("Bob", 30), new Person("Charlie", 35), new Person("Bob", 35) ); Map<String, Map<Integer, List<Person>>> result = people.stream() .collect(Collectors.groupingBy(Person::getName, Collectors.groupingBy(Person::getCity))); } }