如何把第二次存在是2左右?

时间:2017-04-21 04:36:14

标签: java hashmap

如果我的数据第一次存在时如何添加,值将为1,如果数据已存在于hashmap中,则需要输入2,依此类推。

下面是我的编码:

public ArrayList<String> processJson(JSONObject json) {
    HashMap<String, Integer> hm = new HashMap<String, Integer>();
    ArrayList<String> output = new ArrayList<>();
    for (int i = 0; i < hits.length(); i++) {
        // to make sure funny/stupid/illogical resp back from ES is caught and ignored!
        try {
            JSONArray tag = item.getJSONArray("tag");
            System.out.println("tag" + hm.entrySet());
            if (source.equalsIgnoreCase("trkd")) {
                for (int j = 0; j < tag.length(); j++) {
                    if (j == 0) {
                        if (!hm.containsKey(tag.toString(0))) {
                            hm.put(tag.getString(0), 1);
                        } else {
                            hm.put(tag.getString(0), new Integer(j + 1));
                        }
                    }
                }
            }
            if (hm.containsValue(1)) {
                output.add(out);
            } else {
                output.add(out);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return output;
}

如果值等于1,则输出只是添加。 但是现在,我的hashmap都是值1,怎么办?

3 个答案:

答案 0 :(得分:0)

您正在进行比较

if (!hm.containsKey(tag.toString(0))) {

但是用

更新
hm.put(tag.getString(j), 1);

所以j != 0

我猜包含也应该使用j

修改

正如@Adi指出的那样 另外,检查条件'j == 0',这是不必要的,并且阻止您处理超出第一个标记。

答案 1 :(得分:0)

您的代码中发生了许多奇怪的事情。

  1. 非常确定MinPlayersMaxPlayers不相同。我打赌你只想使用Source: local data frame [11 x 4] Groups: MinPlayers [2] Game Rating MinPlayers MaxPlayers <fctr> <dbl> <dbl> <dbl> 1 A 6.0 3 6 2 B 7.0 3 7 3 C 6.5 3 6 4 D 7.0 3 6 5 E 7.0 3 5 6 F 9.5 2 5 7 G 6.0 2 4 8 H 7.0 2 4 9 I 6.5 2 4 10 J 7.0 2 2 11 K 7.0 2 4

  2. 为什么一切都发生在tag.toString(int)条款中?你的循环实际上只会做一次有用的东西。

  3. 你真的想尝试这样的代码吗?

    tag.getString(int)
  4. 以下代码并不需要getString,因为您在两种情况下都做同样的事情。

    j==0

    可替换为:

    if (!hm.containsKey(tag.getString(j))) {
        hm.put(tag.getString(j), 1);
    } else {
        hm.put(tag.getString(j), hm.get(tag.getString(j)+1);
    }
    
  5. 我不认为你很好地解释了你需要做什么。无论我使用#3中的代码收集什么,都可以得到你想要的东西。

答案 2 :(得分:0)

您应该使用Multimap而不是HashMap。 Google Guava提供了一个。