CLOVIS
07/15/2026, 3:22 PM.associateSingle & family?
Inspired by:
• `.first`: Takes the first element, ignores others
• `.single`: Takes the first element, throws if there are others
• .group : groups, putting duplicates into a list
• .associate : groups, ignoring duplicates
• .associateSingle : groups, same signature as .associate , but throws an exception if there are duplicatesCLOVIS
07/15/2026, 3:30 PMval foo = list.groupingBy { it.key }
.eachSingle()
which can be implemented as
fun <Key, Value> Grouping<Value, Key>.eachSingle(): Map<Key, Value> {
return this
.fold(
initialValueSelector = { _, element ->
element
},
operation = { key, accumulator, element ->
throw IllegalArgumentException("""
Collection contains multiple elements matching key $key:
- First element: $accumulator
- Second element: $element
""".trimIndent())
}
)
}Vsevolod Tolstopyatov [JB]
07/15/2026, 5:34 PMVsevolod Tolstopyatov [JB]
07/15/2026, 5:35 PMCLOVIS
07/15/2026, 6:04 PMCLOVIS
07/15/2026, 6:05 PMVsevolod Tolstopyatov [JB]
07/15/2026, 6:52 PMassociateBy (whether it has the right default is a different story), and to use an alternative, one actually has to think whether they don't need the regular associateBy anywayCLOVIS
07/15/2026, 6:53 PMHunter
08/17/2026, 10:30 PM.associateByTo(WriteOnceMap()) { ... }
As a side note, I've typically called these write-once maps in my code Registry. I have no idea if there's a more 'correct' term for it.