`list.fold(mapOf()) { a, c -> a + c }`
# getting-started
k
list.fold(mapOf()) { a, c -> a + c }
h
Thanks!
k
It's going to be quite inefficient if
list
is large, so be careful.
p
this would be more efficient, right?
Copy code
list.fold(mutableMapOf<Int, Int>()) { a, b ->
	a.putAll(b)
	a
}
👍 1
k
Yeah, unfortunately it's ugly, arguably an abuse of
fold
and it returns something mutable.
Copy code
mutableMapOf().apply { list.forEach { putAll(it) } as Map
would be another solution.
h
kotlin should get collectEntries() from groovy 🙂
p
not necessarily more efficient, but definitely fun:
Copy code
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
How about
Copy code
list.reduce { acc, map -> acc + map  }
Same caveats about large lists apply of course
👍 1
k
Doesn't work if
list
is empty!
✔️ 1