将键映射到列表的匹配列表的惯用方式是什么?一个例子-给出:
val s = listOf(1, 9)
val u = listOf(listOf(1, 2, 3), listOf(1, 4, 7), listOf(1, 5, 9))
我想要一个
Map<Int, List<List<Int>>>
,以便s
中的每个键都映射到包含该键的列表的列表中:{1=[ [1, 2, 3], [1, 4, 7], [1, 5, 9] ], 9=[ [1, 5, 9] ]}
以下:
s.groupBy({ it }, { x -> u.filter { it.contains(x) } })
产生:
{1=[[[1, 2, 3], [1, 4, 7], [1, 5, 9]]], 9=[[[1, 5, 9]]]}
这不太正确,也不清楚如何将结果展平为预期的形状。
最佳答案
我会推荐 associateWith
并像这样使用它:
s.associateWith { num -> u.filter { list -> num in list } }
输出:
我最初建议使用
associate
,但是如果使用associateWith
,则可以进一步缩短代码。感谢Abhay Agarwal推荐了它。