简体   繁体   English

在 Kotlin 中递增 hash map 计数

[英]incrementing hash map count in Kotlin

I have the function below.我有下面的 function。 However, when I pass a string to it, I get the following error:但是,当我将字符串传递给它时,会出现以下错误:

error: operator call corresponds to a dot-qualified call 'charCountMap.get(c).plus(1)' which is not allowed on a nullable receiver 'charCountMap.get(c)'. charCountMap.put(c, charCountMap.get(c) + 1)

private fun characterCount(inputString:String) {
  val charCountMap = HashMap<Char, Int>()
  val strArray = inputString.toCharArray()
  for (c in strArray)
  {
    if (charCountMap.containsKey(c))
    {
      charCountMap.put(c, charCountMap.get(c) + 1)
    }
    else
    {
      charCountMap.put(c, 1)
    }
  }
  
  
}

The Kotlin Standard Library has groupingBy and eachCount for this purpose, you don't need to do any of this manually: Kotlin 标准库为此目的具有groupingByeachCount ,您无需手动执行任何操作:

private fun characterCount(inputString:String) {
    val charCountMap : Map<Char, Int> = inputString.groupingBy { it }.eachCount()
}

Note that I put the type on charCountMap for clarity, but it can be left off and inferred.请注意,为了清楚起见,我将类型放在 charCountMap 上,但可以省略并推断。

There is nice compute method in HashMap for this: HashMap中有很好的计算方法:

private fun characterCount(inputString:String) = hashMapOf<Char, Int>().also { charCountMap ->
    inputString.forEach { charCountMap.compute(it) { _, v -> if (v == null) 1 else v + 1 } }
}

Both the other answers are correct.其他两个答案都是正确的。 Todd's answer is right, you don't need to write a function for this. Todd 的回答是对的,你不需要为此写一个 function。 Just use the standard library.只需使用标准库。 And if you are going to write a function that updates maps, Михаил Нафталь's suggestion to use compute() to handle updating existing values is also good.如果您要编写更新地图的 function, Михаил Нафталь 的建议使用compute()来处理更新现有值也很好。


However, if you're just doing this an an exercise, here are three suggestions to fix/improve your algorithm:但是,如果您只是在做一个练习,这里有三个建议来修复/改进您的算法:

  1. Instead of get() , use getValue() , which does not return null.使用getValue()代替get() ,它不会返回 null。 It will raise an exception if the element does not exist, but you already checked for that.如果元素不存在,它将引发异常,但您已经检查过了。
  2. Use the [] operator instead of put() (no need to, it's just nicer syntax).使用[]运算符而不是put() (不需要,它只是更好的语法)。
  3. You don't need to call toCharArray() because Strings are already iterable.您不需要调用toCharArray()因为字符串已经是可迭代的。
if (charCountMap.containsKey(c))
{
    charCountMap[c] = charCountMap.getValue(c) + 1
}
else
{
    charCountMap[c] = 1
}

Rewriting the whole thing using standard formatting:使用标准格式重写整个事情:

fun characterCount(inputString: String): Map<Char, Int> {
    val charCountMap = mutableMapOf<Char, Int>()
    for (c in inputString) {
        if (charCountMap.containsKey(c)) {
            charCountMap[c] = charCountMap.getValue(c) + 1
        } else {
            charCountMap[c] = 1
        }
    }
    return charCountMap
}

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

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