简体   繁体   English

如何在 function 中返回带有列表参数的 MutableMap(HashMap) 以查找列表中每个元素的频率 (Kotlin)

[英]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)

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
}

Solution: No need for generic type declaration of the variable list, just add <String> in the function parameter.解决方法:变量列表不需要泛型类型声明,只需在function参数中添加<String>即可。 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
}

Playground link 游乐场链接

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.当您将字符串列表放入类型为 T 的 function 时,它的类型在运行时是未知的,您正在尝试迭代这个未知类型。 Therefore, you must indicate that this object can be used to interact with.因此,您必须指明可以使用此 object 进行交互。

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.在下面的示例中,我们不再像上面那样依赖 String 类型。 But then, at the output, we will get a Map with this type.但随后,在 output 中,我们将获得具有此类型的 Map。

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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM