groupBy
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/group-by.html
    val ids = listOf<String>("id1", "id2", "id2")
    print(ids.groupBy { it })
{id1=[id1], id2=[id2, id2]}
配列を渡して、条件をそれ自体の it にすると
重複しているものをまとめてくれる
    val men = listOf(
        "Ai" to 3,
        "Bot" to 3,
        "Carl" to 5,
        "Dan" to 5,
    )
    print(men.groupBy ({it.second}, {it.first}) )
{3=[Ai, Bot], 5=[Carl, Dan]}
"name": age, のような連想配列を渡して、
2 つめの値で 1 つめの値をまとめるようにかける。
    val men = listOf(
        "id1" to "tom",
        "id1" to "cat",
        "id1" to "bob",
        "id2" to "dog",
    )
    print(men.groupBy ({it.first}, {it.second}) )
{id1=[tom, cat, bob], id2=[dog]}
なのでこのように、おなじ ID の 人の名前をまとめることができる。
id1, id2 のそれぞれの pair 型になっている?
この出力は使いにくいので、toList() すると
[(id1, [tom, cat, bob]), (id2, [dog])]
こうなる
これは map して
id1 が it.first 
[tom, cat, bob] が it.second 
こうやってとることができる。
なので 2 つめの size をとって
    val men = listOf(
        "id1" to "tom",
        "id1" to "cat",
        "id1" to "bob",
        "id2" to "dog",
    )
    val menGroupedById = men.groupBy(
        {it.first}, {it.second}
    ).toList()
    val duplicatedIdAndCount = menGroupedById.map { it ->
        it.first to it.second.size
    }
    print(duplicatedIdAndCount)
[(id1, 3), (id2, 1)]
こうやって重複するキーと重複した数をまとめることができた
まとめ
key:value な連想配列に
arrayName.groupBy({it.first},{it.second})
これをすると、key ごとに value をまとめてくれる。
その後リストにしてmap して 
1 つめ ( key ) と
2 つめ ( key に紐づく value たちの配列 ) の長さ
これをまとめると
key:duplicatedKeyCount の配列が作れる。
    
Top comments (0)