A more efficient (yet still succinct way) to create a freq. map?

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)

values.groupingBy{it}.eachCount()

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/each-count.html

3 Likes

While values.groupingBy{it}.eachCount() looks much better, I doubt that it is more efficient at a relevant level, since the operations und the hood would be similar.

However: Don’t micro-optimize without profiling first! I think in most cases these operations wouldn’t be a bottleneck.

It doesn’t create all those unnecessary lists.

Also… profiling and optimizing takes a lot of time, and it’s triggered by problems you don’t want to have! When you want code to be fast, you should really just know what it does and write appropriately fast code.