Suppose I have a collection of (not necessarily distinct) values,
And I wish to calculate a ‘frequency map’ for that collection.
I figured out a way to do it, using groupBy
and then map
and toMap
:
val values = arrayOf(1, 1, 1, 2, 3, 4, 4)
values.groupBy { it }
.map { (value, eqVals) -> (value to eqVals.size) }
.toMap()
// res0: kotlin.collections.Map<kotlin.Int, kotlin.Int> = {1=3, 2=1, 3=1, 4=2}
My question is:
Is there a better/more-efficient way to do it, which is still that succinct?
(I am particularly interested in getting rid of the superfluous lists of equivalent values, created by groupBy
)