我有一个HashMap,其中包含一个ArrayList作为值。我想检查其中一个列表是否包含对象,并从列表中删除该对象。我怎样才能做到这一点?
我尝试使用一些 for 循环,但后来我得到了一个 ConcurrentModificationException。我无法摆脱这种例外。
我的哈希图:
Map<String,List<UUID>> inAreaMap = new HashMap<String, ArrayList<UUID>>();
我想检查数组列表中是否包含我得到的UUID,如果是,我想把它从数组列表中移除。但是我不知道代码那个位置的字符串。
我已经试过了:
for (List<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);
}
}
}
}
}
有一种更优雅的方法可以做到这一点,使用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));
});
用迭代器试试。inareamap.iterator()..和..iterator.remove()
如果你有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);
}
}