Group by field name in Java

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

    In Scala, this is a feature of the class List already:

    class Person (val name: String, val surname: String ="Smith") 
    val li = List (new Person ("David"), new Person ("Joe"), new Person ("Sue"), new Person ("David", "Miller")) 
    li.groupBy (_.name)
    

    res87: scala.collection.immutable.Map[String,List[Person]] = Map((David,List(Person@1c3f810, Person@139ba37)), (Sue,List(Person@11471c6)), (Joe,List(Person@d320e4)))

    Since Scala is bytecode compatible to Java, you should be able to call that method from Java, if you include the scala-jars.

提交回复
热议问题