【问题标题】:Finding how many times an item has appeared in an array = explaining the code [closed]查找一个项目在数组中出现了多少次=解释代码[关闭]
【发布时间】:2020-01-23 16:39:53
【问题描述】:

您能解释一下这段代码是如何工作的吗? 我无法理解这段代码是如何工作的。

        HashMap<String, Integer> countMap = new HashMap<String, Integer>();
        for (String string : strArray) {
            if (!countMap.containsKey(string)) {
                countMap.put(string, 1);
            } else {
                Integer count = countMap.get(string);
                count = count + 1;
                countMap.put(string, count);
            }
        }
        printCount(countMap);
    }


    private static void printCount(HashMap<String, Integer> countMap) {
        Set<String> keySet = countMap.keySet();
        for (String string : keySet) {
            System.out.println(string + " : " + countMap.get(string));
        }
    }
}

【问题讨论】:

  • geeksforgeeks.org/count-occurrences-elements-list-java 应该解释更多。基本概念是将数组中的字符串作为键放在 hashmap 中,然后增加每次出现的计数。如果某个特定字符串不在 hashmap 中,则将该字符串添加为键并将计数设为 1,然后从那里继续增加计数。
  • 谢谢。您的链接非常有用。那是什么意思:?整数 j = count.get(i); count.put(i, (j == null) ? 1 : j + 1);
  • 让我为你分解一下:Integer j = count.get(i); 从哈希图中获取 i 的当前计数。 count.put(i, 部分以 i 作为键放入 hashmap。 (j == null) ? 1 : j + 1) 检查当前计数是否为空(意味着要添加的项目不在地图中)初始化计数为 1 否则获取当前计数并增加 1。希望这是有道理的。

标签: java methods count hashmap items


【解决方案1】:

最初,您的 hashmap 不包含任何值

 HashMap<String, Integer> countMap = new HashMap<String, Integer>();

现在,您正在对所谓的字符串列表运行一个循环,即 strArray。

  for (String string : strArray) {

在这里您正在检查您的地图是否包含迭代键,即字符串

它在第一次迭代中没有(或任何不在 countmap 中的键),所以它把字符串作为键和 1 作为值

  if (!countMap.containsKey(string)) {              
     countMap.put(string, 1);
        } else {

如果 countMap 包含字符串,那么您将获取给定键的值,并在该值中添加一个并将其放回 countmap(基本上用递增值替换旧值)

            Integer count = countMap.get(string);
            count = count + 1;
            countMap.put(string, count);
        }

    }

稍后,您将打印密钥及其值。

   printCount(countMap);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-04
    • 2019-04-02
    • 2021-01-16
    • 1970-01-01
    相关资源
    最近更新 更多