Group by field name in Java

前端 未结 7 1871
迷失自我
迷失自我 2020-12-01 05:35

I\'m trying to group Java objects by their field, i.e Person.java

public class Person {
    String name;
    String surname;
    ....
}
7条回答
  •  没有蜡笔的小新
    2020-12-01 06:28

    Using java-8 with the Collectors class and streams, you can do this:

    Map> mapByName = 
        allPeople.stream().collect(Collectors.groupingBy(Person::getName));
    
    List allDavids = mapByName.getOrDefault("David", Collections.emptyList());
    

    Here I used getOrDefault so that you get an empty immutable list instead of a null reference if there is no "David" in the original list, but you can use get if you prefer to have a null value.

    Hope it helps! :)

提交回复
热议问题