简体   繁体   中英

Remove object from hashmap based on key attribute in Java

I have an Identifier class that looks like this:

private final Integer year;
private final Integer month;

...

@Override
public boolean equals(Object o) {
    ...
}

@Override
public int hashCode() {
    ...
}

I want to use this class as the key in a ConcurrentHashMap .

Something like ConcurrentHashMap<Identifier, Object>

Objects are always identified by year and month, which means that this class is useful to find the object and still use the concurrent property of the hashmap.

Now, in some situations I want to remove all objects related to some specific year. Is there a way to do this easily?

Or should I just create a double ConcurrentHashMap ? ConcurrentHashMap<Integer, ConcurrentHashMap<Integer, Object>>

I'm not sure it would be the same thing. And if for some reason I wanted to delete by month it wouldn't work.

If you use ConcurrentHashMap<Identifier, Object> , you'll have to iterate all entries of the map and delete required objects.

It is not possible to override equals & hashCode to achieve what you want.

If you override the above-mentioned methods to treat 2 objects with the same year as equal, you won't be able to store multiple objects with the same year & different months in the map because doing that will replace the old object since they both are equal.


However, this setup ConcurrentHashMap<Integer, ConcurrentHashMap<Integer, Object>> can work for you.

I think it is not possible to do that using equals, hashcode cause you already defined them in your Identifier class using both year and month, so you can't change them just to use year field cause it will override elements in your map even if month is different.

public class Application {
public static void main(String[] args) {
    ConcurrentHashMap<Identifier, String> map = new ConcurrentHashMap<>();
    map.put(new Identifier(2020,1), "1");
    map.put(new Identifier(2020,2), "2");
    map.put(new Identifier(2021,3), "3");
    map.put(new Identifier(2021,4), "4");
    map.put(new Identifier(2021,1), "5");

    System.out.println(map.size()); // 5
    removeElementsByYear(map, 2020);
    System.out.println(map.size()); // 3
}

private static void removeElementsByYear(ConcurrentHashMap<Identifier, String> map, int year) {
    for(Identifier key : map.keySet()) {
        if (key.getYear() == year) {
            map.remove(key);
        }
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM