是否可以将以下嵌套的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)
}
答案 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)
}