![](/img/trans.png)
[英]What's the quickest way to remove an element from a Map by value in Java?
[英]What's the quickest way to remove an element from a Map By Key in Java?
有一個Object的例子,提交的id是唯一的。
我假設 map 中有很多元素,從 map 中刪除 id = 1 示例的最快方法是什么。
public class Solution {
@Data
public static class Example {
// unique key
int id;
Object filed;
}
public static void main(String[] args) {
// Suppose there are many elements in the map
HashMap<Example, Object> map = new HashMap<>();
int id = 1;
Example example = new Example();
example.setId(id);
map.put(example, new Object());
// How to quickly delete example of id = 1
System.out.println(map);
}
}
您必須覆蓋Example
class 中的equals
和hashCode
方法。 發布當您調用 map.remove(example) 時,它將刪除它。 在您的equals
和hashCode
方法中,您必須使用字段id
作為相等或比較因子。
class Example {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Example)) return false;
Example that = (Example) o;
return id == that.id;
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
注意:以上不是編譯代碼,只是一個片段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.