我正在尝试了解HashMaps,并希望获得一些删除值的帮助(在这种情况下,地方)。我有3个HashMaps(perName,perCategory,perPosition),其中2个具有作为值的位置列表,并且所有字符串/位置都作为键。因此,可以存在具有相同名称或类别的不同地方。我希望从每个HashMap的值列表中删除某个位置,具体取决于该位置是否标记为"或不。
每个添加的位置都存储在所有HashMaps中,标记的位置存储在单独的ArrayList中。我试图遍历ArrayList并从每个HashMap中删除它的每个位置/值。我不想删除密钥,因为可能有其他没有标记的地方使用相同的密钥。这可能吗?目前,当我试图将它们移除时,这些地方似乎不会消失。
我尝试了不同的方法,带有迭代器的方法(可能是不必要的)似乎删除了整个键,而带有for循环的方法根本没有删除任何东西。如果我没有提供足够的信息来解决这个问题,请告诉我。谢谢。
private Map<Position, Place> perPosition = new HashMap<>();
private Map<String, List<Place>> perCategory = new HashMap<>();
private Map<String, List<Place>> perName = new HashMap<>()
//method 1
Iterator<Place> it = markedPlace.iterator();
while (it.hasNext()) {
Place p = it.next();
perPosition.remove(p.getPosition());
perName.remove(p.getName());
perCategory.remove(p.getCategory());
p.setMarked(false);
p.setVisible(false);
it.remove();
}
//method 2
for (Place p : markedPlace) {
for (Map.Entry<String, List<Place>> entry : perName.entrySet()) {
if (entry.getValue().equals(p)) {
perName.remove(entry.getValue());
}
}
for (Map.Entry<String, List<Place>> entry : perCategory.entrySet()) {
if (entry.getValue().equals(p)) {
perCategory.remove(entry.getValue());
}
}
for (Map.Entry<Position, Place> entry : perPosition.entrySet()) {
if (entry.getValue().equals(p)) {
perName.remove(entry.getKey());
}
}
markedPlace.clear();
答案 0 :(得分:2)
entry.getValue()的类型为List<Place>
,p为类型Place
。因此对于perName和perCategory循环,equals永远不会成立。您需要使用.contains(foo)
来检查对象是否在列表中。
然后,您尝试清除要保留的列表。您想要从列表中删除条目,而不是地图。
if (entry.getValue().contains(p)) {
entry.getValue().remove(p);
}
然后List支持remove collection,因此您只需执行
即可for (Map.Entry<String, List<Place>> entry : perName.entrySet()) {
entry.getValue().remove(markedPlace);
}
此外,在Place类中,请确保覆盖equals和hashcode,否则只有两个Place对象都是完全相同的实例化对象时才会匹配。
答案 1 :(得分:0)
Java的Map remove方法需要一个键才能删除。在其中两种情况下,您传递的值不是密钥。
https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#remove-java.lang.Object-