Group by field name in Java

前端 未结 7 1881
迷失自我
迷失自我 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:14

    You can use Multimap and groupBy() from Eclipse Collections

    MutableList allPeople = Lists.mutable.empty();
    MutableListMultimap multimapByName = allPeople.groupBy(Person::getName);
    

    If you can't change the type of allPeople from List

    List allPeople = new ArrayList<>();
    MutableListMultimap multimapByName = 
         ListAdapter.adapt(allPeople).groupBy(Person::getName);
    

    Note: I am a contributor to Eclipse Collections.

提交回复
热议问题