嵌套组由科特林

时间:2019-02-24 10:54:16

标签: kotlin collections group-by

是否可以将以下嵌套的groupingBy转换为等效的Kotlin Collections?

运行以下代码:https://rextester.com/IYJ63609

fun main(args: Array<String>) {
    data class Person(val name: String, val city: String, val phone: String)

    val people = listOf(
            Person("John", "Boston", "+1-888-123456"),
            Person("Svyatoslav", "Saint-Petersburg", "+7-999-456700"),
            Person("Svyatoslav", "Saint-Petersburg", "+7-999-456789"),
            Person("Vasilisa", "Saint-Petersburg", "+7-999-123456"))

    val phoneBook = people.stream().collect(
      java.util.stream.Collectors.groupingBy(Person::city, 
        java.util.stream.Collectors.groupingBy(Person::name)
      )
    )
    println(phoneBook)
}

1 个答案:

答案 0 :(得分:1)

顺序有点不同,但是可以,

fun main(args: Array<String>) {
    data class Person(val name: String, val city: String, val phone: String)

    val people = listOf(
            Person("John", "Boston", "+1-888-123456"),
            Person("Svyatoslav", "Saint-Petersburg", "+7-999-456700"),
            Person("Svyatoslav", "Saint-Petersburg", "+7-999-456789"),
            Person("Vasilisa", "Saint-Petersburg", "+7-999-123456"))

    val phoneBook = people.groupBy(Person::city)
                          .mapValues { (_, v) -> v.groupBy(Person::name) }
    println(phoneBook)
}