Reputation: 99
I have Map<String, Map<String, Int>>
.
How should I analyze it? I want to count how many values there are for each key.
Let's say we have a map like: {jack={a=1, b=2, c=3}, amy={d=1, a=3, c=1, e=5}
My aim is to getting the number of elements by each key of the map, something like: [jack=3, amy=4]
Upvotes: 1
Views: 2653
Reputation: 8705
In Kotlin you only need to init your list as a Hashmap, then you can easily iterate on the hashMap and get keys and elements count:
val hashMap = hashMapOf(
"jack" to mapOf("a" to 1, "b" to 2, "c" to 3),
"amy" to mapOf("d" to 1, "a" to 3, "c" to 1, "e" to 5)
)
for (e in hashMap) {
println("Key: ${e.key}, elementsCount: ${e.value.size}, elements: ${e.value}")
}
Upvotes: 0
Reputation: 21043
You can iterate over Map and get the Entry for each key .
for (Map.Entry<String, Map<String, Integer>> entry : map.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue().size());
}
Kotlin equivalent will be
for ((key, value) in map) {
println(key + " = " + value.size)
}
If you are only interested in size then this will do .
You can further use entry.getValue()
to iterate over inner map in case you need further data.
Upvotes: 1