0

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

我尝试过使用一些 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);
                }
            }
        }
    }
}
4

4 回答 4

2

有一种更优雅的方法可以做到这一点,使用 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));
});
于 2019-08-09T13:30:20.230 回答
1

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

于 2019-08-09T13:27:33.397 回答
0

如果你有 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);
    }
}
于 2019-08-09T14:01:14.970 回答
0

这里是简单的解决方案。

    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();
        }
    }
于 2019-08-10T01:35:18.070 回答