https://kotlinlang.org logo
Title
k

karelpeeters

10/29/2018, 3:03 PM
list.fold(mapOf()) { a, c -> a + c }
h

henrik

10/29/2018, 3:05 PM
Thanks!
k

karelpeeters

10/29/2018, 3:06 PM
It's going to be quite inefficient if
list
is large, so be careful.
p

potter

10/29/2018, 3:09 PM
this would be more efficient, right?
list.fold(mutableMapOf<Int, Int>()) { a, b ->
	a.putAll(b)
	a
}
👍 1
k

karelpeeters

10/29/2018, 3:11 PM
Yeah, unfortunately it's ugly, arguably an abuse of
fold
and it returns something mutable.
mutableMapOf().apply { list.forEach { putAll(it) } as Map
would be another solution.
h

henrik

10/29/2018, 3:16 PM
kotlin should get collectEntries() from groovy 🙂
p

potter

10/29/2018, 3:16 PM
not necessarily more efficient, but definitely fun:
list.flatMap { it.entries.map { it.toPair() } }.toMap()
(not sure if there's a better way to get pairs from a list of maps)
j

Joris PZ

10/29/2018, 3:22 PM
How about
list.reduce { acc, map -> acc + map  }
Same caveats about large lists apply of course
👍 1
k

karelpeeters

10/29/2018, 6:44 PM
Doesn't work if
list
is empty!
✔️ 1