fork(1) download
  1. import java.util.*;
  2. import java.util.stream.*;
  3. import static java.util.stream.Collectors.*;
  4.  
  5. class Person {
  6. final String name, surname;
  7. public Person(String n, String s){
  8. this.name = n;
  9. this.surname = s;
  10. }
  11. public String getName(){ return name; }
  12. public String getSurname(){ return surname; }
  13. }
  14.  
  15. class Ideone {
  16.  
  17. public static void main(String[] args) {
  18. List<Person> people = Arrays.asList(
  19. new Person("Sam", "Rossi"),
  20. new Person("Sam", "Verdi"),
  21. new Person("John", "Bianchi"),
  22. new Person("John", "Rossi"),
  23. new Person("John", "Verdi")
  24. );
  25.  
  26. Map<String, List<String>> map = people.stream()
  27. .collect(
  28. // function mapping input elements to keys
  29. groupingBy(Person::getName,
  30. // function mapping input elements to values,
  31. // how to store values
  32. mapping(Person::getSurname, toList()))
  33. );
  34. System.out.println(map);
  35. }
  36. }
Success #stdin #stdout 0.09s 711680KB
stdin
Standard input is empty
stdout
{John=[Bianchi, Rossi, Verdi], Sam=[Rossi, Verdi]}