This small example demonstrates the usage of Collectors.groupingBy to group a list of Persons by their age. The mapped result is a map of list with all Persons of the same age.
public class Person {
private Integer age;
private String name;
public Person(Integer age, String name) {
this.age = age;
this.name = name;
}
public Integer getAge() {
return age;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "Person{age=" + age + ", name='" + name + "\'}";
}
}
Now group them with Collectors.groupingBy
:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.toList;
public class Grouping {
private static final Logger logger = LoggerFactory.getLogger(Grouping.class);
public static void main(String[] args) {
List<Person> people = Arrays.asList(new Person(22, "Alice"),
new Person(45, "Bob"),
new Person(22, "Cindy"),
new Person(4, "Deborah"));
Map<Integer, List<Person>> grouped = people.stream()
.collect(Collectors.groupingBy(Person::getAge,
mapping(Function.identity(), toList())));
logger.info("grouped: {}", grouped);
}
Output:
grouped: {
4=[Person{age=4, name='Deborah'}],
22=[Person{age=22, name='Alice'}, Person{age=22, name='Cindy'}],
45=[Person{age=45, name='Bob'}]
}