[英]How to collect a stream of pairs in kotlin?
如何在Kotlin中收集成對的溪流? 因此,在Java中,我通常這樣做:
Stream.of("1", "2", "3").map(x -> new AbstractMap.SimpleEntry<>(x, x)).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))
但是在科特林,
Stream.of("1", "2", "3").map{ x -> x to x }
返回成對的流,我找不到收集該流的方法。
在Kotlin中,使用listOf()
比使用Java的Stream.of()
更自然。 一旦有了List<Pair>
,就可以使用.toMap()
擴展.toMap()
它們變成地圖!
val myMap: Map<String, String> = listOf("1", "2", "3").map{ it to it }.toMap()
在給定一個lambda的情況下, List
上還有一個.associate()
函數可以為您創建一個地圖:
val myMap2: Map<String, String> = listOf("1", "2", "3").associate { it to it }
那個看起來比較干凈,恕我直言。
由於您將list元素本身用作鍵,因此使用associateWith可使代碼更加簡潔:
val myMap = listOf("1", "2", "3").associateWith{ it }
結果:
{1 = 1,2 = 2,3 = 3}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.