fun main() {
val list = listOf("B", "A", "A", "C", "B", "A")
print(findfrequency(list))
}
fun <T> findfrequency(list: T): MutableMap<String, Int> {
val frequencyMap: MutableMap<String, Int> = HashMap()
for (s in list) {
var count = frequencyMap[s]
if (count == null) count = 0
frequencyMap[s] = count + 1
}
return frequencyMap
}
How would you return a MutableMap(HashMap) with a list parameter in a function to find the frequency of each element in the list (Kotlin)
562 Views Asked by TheDevTing AtThere are 2 best solutions below
On
When you put a list of strings into a function with type T, its type is unknown at runtime, and you are trying to iterate over this unknown type. Therefore, you must indicate that this object can be used to interact with.
fun main() {
val list = listOf("B", "A", "A", "C", "B", "A")
print(findfrequency(list))
}
fun <T : Iterable<String>> findfrequency(list: T): MutableMap<String, Int> {
val frequencyMap: MutableMap<String, Int> = HashMap()
for (s in list) {
var count = frequencyMap[s]
if (count == null) count = 0
frequencyMap[s] = count + 1
}
return frequencyMap
}
In the example below, we are no longer dependent on the String type, as it was above. But then, at the output, we will get a Map with this type.
fun <T : Iterable<S>, S> findfrequency(list: T): MutableMap<S, Int> {
val frequencyMap: MutableMap<S, Int> = HashMap()
for (s in list) {
var count = frequencyMap[s]
if (count == null) count = 0
frequencyMap[s] = count + 1
}
return frequencyMap
}
Solution: No need for generic type declaration of the variable list, just add
<String>in the function parameter. Here is the final program:Playground link