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
}
Asked
Active
Viewed 398 times
0

sidgate
- 14,650
- 11
- 68
- 119

TheDevTing
- 11
- 2
-
1why `list` parameter in `findfrequency` of generic type T and not of explicit type `List
`? – sidgate Apr 09 '21 at 03:41 -
Also, why do you need to return mutable map? Simple solution is `list.groupingBy { it }.eachCount()` – sidgate Apr 09 '21 at 03:44
-
Thankyou @sidgate – TheDevTing Apr 09 '21 at 05:38
2 Answers
1
Solution: No need for generic type declaration of the variable list, just add <String>
in the function parameter.
Here is the final program:
fun main() {
val list_String = listOf("B", "A", "A", "C", "B", "A")
println(findfreq(list_String))
}
fun findfreq(list: List<String>): MutableMap<String, Int> {
val frequencyMap: MutableMap<String, Int> = HashMap()
for(i in list) {
var count = frequencyMap[i]
if(count == null) count = 0
frequencyMap[i] = count + 1
}
return frequencyMap
}

spender
- 117,338
- 33
- 229
- 351

TheDevTing
- 11
- 2
-
3Can you add the actual code to the answer? External links can get broken. – matt freake Apr 09 '21 at 06:12
0
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
}

Andrey Romanyuk
- 31
- 1
- 4