Total size of HashMap flatten elements

Hello, is there a hashMapOf<String, MutableList<String>>() method returns total size of all elements in O(1)? Guys there just like me still make it old style forEach way.

There is nothing really “old” in using forEach() or loops. But if you are looking for functional way of doing this then:

z.values.sumOf { it.size }

If you’re looking for something similar to SO question, so create Map<String, Int> as a result then:

z.mapValues { it.value.size }

1 Like

Hm, even if it’s not O(1), at least it’s a 1-string method. Is there a case this method is used often or it’s hard to implement this variable?

I don’t think it is possible to do it in O(1). This data structure is basically a collection of collections, so we really need to iterate and count items. You can always create your own data structure that counts elements while adding them.

Sorry, I don’t understand the last sentence in your post.

I meant - can a new variable be implemented in a base map class - if it contains iterables, increase the total size of the map counting all its elements?

You can create your own data structure that implements MutableMap<String, MutableList<String>> and does this.