我有一个 HashMap,其中包含一个 ArrayList 作为值。我想检查其中一个列表是否包含一个对象并从列表中删除该对象。我怎样才能实现这一目标?
我尝试使用一些 for 循环,但随后出现 ConcurrentModificationException。我无法消除该异常。
我的 HashMap :
Map<String,List<UUID>> inAreaMap = new HashMap<String, ArrayList<UUID>>();
我打算检查 ArrayList 是否包含我获得的 UUID,如果是,我想将其从该 ArrayList 中删除。但我不知道代码中该位置的字符串。
我已经尝试过的:
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));
});
关于java - 从嵌套在 Map 中的 List 中删除值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57431057/