【问题标题】:Remove a value from a arraylist who is in a hashmap从哈希图中的数组列表中删除一个值
【发布时间】:2019-12-17 06:06:39
【问题描述】:

我有一个包含数组列表作为值的哈希图。我想检查其中一个数组列表是否包含一个对象,然后从数组列表中删除该对象。但是,怎么做?

我尝试过使用一些 for 循环,但我得到了 ConcurrentModificationException,我无法消除该异常。

我的哈希图:

HashMap<String,ArrayList<UUID>> inareamap = new HashMap<String, ArrayList<UUID>>();

我想检查 ArrayList 是否包含我拥有的 UUID,如果是,我想从该 ArrayList 中删除它。但是我不知道代码那个位置的字符串。

我已经尝试过的:

for (ArrayList<UUID> uuidlist : inareamap.values()) {
    for (UUID uuid : uuidlist) {
        if (uuid.equals(e.getPlayer().getUniqueId())) {
            for (String row : inareamap.keySet()) {
                if (inareamap.get(row).equals(uuidlist)) {
                    inareamap.get(row).remove(uuid);
                }
            }
        }
    }
}

【问题讨论】:

  • 哈希图不是问题,您正在尝试删除列表的对象,同时循环抛出它。要解决这个问题,你必须使用 iterator.remove 见stackoverflow.com/questions/223918/…
  • @user43968 感谢您的回复!我尝试过使用迭代器,但我不知道如何将它与 hashmap 结合使用。
  • 另外,我建议在定义类型时使用List 代替ArrayList,程序是接口,而不是实现。

标签: java arraylist hashmap keyset


【解决方案1】:

有一种更优雅的方法可以做到这一点,使用 Java 8:

Map<String, ArrayList<UUID>> map = ...
UUID testId = ...
// defined elsewhere

// iterate through the set of elements in the map, produce a string and list for each
map.forEach((string, list) -> { 

    // as the name suggests, removes if the UUID equals the test UUID
    list.removeIf(uuid -> uuid.equals(testId));
});

【讨论】:

    【解决方案2】:

    尝试使用迭代器。 inareamap.iterator().. 和.. iterator.remove()

    【讨论】:

    • 低质量的答案。您最好提供不那么简短的代码示例
    【解决方案3】:

    如果你有Java 8,camaron1024的解决方案是最好的。否则,您可以利用您有一个列表并按索引向后遍历它的事实。

    for(ArrayList<UUID> uuidlist : inareamap.values()) {
        for(int i=uuidlist.size()-1;i>=0;i--) {
            if (uuidlist.get(i).equals(e.getPlayer().getUniqueId()))
                uuidlist.remove(i);
        }
    }
    

    【讨论】:

      【解决方案4】:

      这里是简单的解决方案。

          UUID key = ... ;
          for(Map.Entry<String,ArrayList<UUID>> e : hm.entrySet()){
              Iterator<UUID> itr = e.getValue().iterator();
              while(itr.hasNext()){
                  if(itr.next() == key)
                      itr.remove();
              }
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-07
        • 2015-08-20
        • 2018-07-27
        • 2015-09-03
        • 2015-04-04
        • 1970-01-01
        • 1970-01-01
        • 2013-11-09
        相关资源
        最近更新 更多