https://kotlinlang.org logo
#announcements
Title
# announcements
d

diesieben07

08/01/2017, 3:08 PM
You could do something like this:
Copy code
val list = listOf("hello" to "world", "hello" to "world2", "bla" to "quz")
val result = list.groupingBy { it.first }.fold(null as String?) { acc, elem -> acc ?: elem.second }
Or, maybe better:
Copy code
val list = listOf("hello" to "world", "hello" to "two worlds", "bla" to "quz")
val result = list.groupingBy { it.first }.aggregate { _, acc: String?, elem, _ -> acc ?: elem.second }
i

iex

08/01/2017, 3:17 PM
looks good, thanks! I was thinking also using just
map
- similar to what you did with
aggregate
but I think I'll write an extension
groupBySingle
or similar to do it in one step
d

diesieben07

08/01/2017, 3:18 PM
The nice thing about using
groupingBy
is that it does not construct and intermediary
Map<K, List<V>>
for the grouping.
It directly applies your aggregation using the source iterator.
i

iex

08/01/2017, 3:18 PM
okay...
d

diesieben07

08/01/2017, 3:19 PM
You can of course use
groupingBy
like I showed in your extension function 😉
i

iex

08/01/2017, 3:24 PM
I thought about that, thanks!
2 Views