使用计数器将数组插入到散列映射中

时间:2017-05-03 14:12:14

标签: java arrays count insert hashmap

所以我在理解这段代码时遇到了一些困难。 for-each从数组中输入字符串以及计数器来计算相同字符串的数量,但计数器如何执行此操作?

Integer count = map.get(nextString);

传递给计数器的号码是多少?

if语句会做什么?

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

    for (String nextString : inArray) {

        Integer count = map.get(nextString);

        if (count == null) {

        count = 1;

        } else {

        count = count + 1;

        }

        map.put(nextString, count);

    }

1 个答案:

答案 0 :(得分:2)

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

这只是初始化我们的HashMap,没什么复杂的。

for (String nextString : inArray) {

    Integer count = map.get(nextString);

这里我们正在寻找与相关联的(在本例中是我们数组中的String)。

    if (count == null) {

        count = 1;

因为我们用给定字符串出现的次数更新映射,如果 no 值与我们的键关联,则此字符串尚未计算,因此我们设置{{ 1}}到1,因为它是我们数组中第一次出现这个String。

count

如果上面的if语句没有执行,那就意味着有一些与字符串相关的值,所以我们可以增加它然后把它放回到地图中。

    } else {

        count = count + 1;