![](/img/trans.png)
[英]From a HashMap, how to remove k number of elements with the highest values(Java)?
[英]How to remove a value from HashMap with list of values in Java?
我正在尝试了解 HashMaps 并希望在删除值(在本例中为位置)方面获得一些帮助。 我有 3 个 HashMap(perName、perCategory、perPosition),其中 2 个将位置列表作为值,并且都将字符串/位置作为键。 因此,可能存在具有相同名称或类别的不同地方。 我想根据该位置是否被“标记”从每个 HashMap 的值列表中删除某个位置。
每个添加的地方都存储在所有的HashMap中,标记的地方存储在单独的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();
entry.getValue() 是List<Place>
类型, p 是Place
类型。 因此,对于 perName 和 perCategory 循环,equals 永远不会为真。 您需要使用.contains(foo)
来检查对象是否在列表中。
然后,您尝试清除要保留的列表。 您想从列表中删除条目,而不是地图。
if (entry.getValue().contains(p)) {
entry.getValue().remove(p);
}
然后 List 支持删除集合,所以你可以简单地做
for (Map.Entry<String, List<Place>> entry : perName.entrySet()) {
entry.getValue().remove(markedPlace);
}
此外,在 Place 类中,确保覆盖 equals 和 hashcode,否则只有当两个 Place 对象是完全相同的实例化对象时才会匹配。
Java 的 Map remove 方法需要一个键来删除。 在其中两种情况下,您传递的是值而不是键。
https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#remove-java.lang.Object-
Two HashMap given below-
hmap2 - >{Competitor=[aaa, bbb, 000, 111], Contractor=[ccc, ddd, 222, 333]}
hmap 1 ->{Competitor=[aaa, bbb], Contractor=[ccc, ddd]}
Below is the code to remove hmap1 from hmap2 - >
for (Map.Entry<String, List<String>> entry : hmap2.entrySet()) {
for (Map.Entry<String, List<String>> tobeDeleted : hmap1.entrySet()) {
List<String> li = tobeDeleted.getValue();
for (String li1 : li) {
entry.getValue().remove(li1);
}
}
}
System.out.println(hmap2);
Output - >{Competitor=[000, 111], Contractor=[222, 333]}
Happy Learning :)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.