Java Stream How to - Map Person List to Integer-Person List Map








Question

We would like to know how to map Person List to Integer-Person List Map.

Answer

/*from  w w  w  . jav a 2 s  .  c  o  m*/
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {

  public static void main(String[] args) throws Exception {
    List<Person> persons =
        Arrays.asList(
            new Person("Max", 18),
            new Person("Peter", 23),
            new Person("Pamela", 23),
            new Person("David", 12));   
    

    Map<Integer, List<Person>> personsByAge = persons
        .stream()
        .collect(Collectors.groupingBy(p -> p.age));

    personsByAge
        .forEach((age, p) -> System.out.format("age %s: %s\n", age, p));
  }

}
class Person {
  String name;
  int age;

  Person(String name, int age) {
      this.name = name;
      this.age = age;
  }

  @Override
  public String toString() {
      return name;
  }
}

The code above generates the following result.