Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Java 8 map.remove to Java 1.6?

Tags:

java

I have the following:

     fruitMap.remove(fruitId, fruitProperties);

The fruitMap is:

private Map<FruitId, FruitProperties> fruitMap = new HashMap<FruitId, FruitProperties>();

When I attempt to build my code I get a:

ERROR
The method remove(Object) in the type Map<MyImplementation.FruitId, FruitProperties>
is not applicable for the arguments (Map<MyImplementation.FruitId, FruitProperties>)

What is the issue?

Note that thiis call is inside of a method "removeFruit()" inside my "FruitImplementation" class.

like image 608
Rolando Avatar asked Jan 17 '15 00:01

Rolando


4 Answers

From the Javadocs:

The default implementation is equivalent to, for this map:

if (map.containsKey(key) && Objects.equals(map.get(key), value)) {
     map.remove(key);
     return true;
 } else
     return false;

The default implementation makes no guarantees about synchronization or atomicity properties of this method. Any implementation providing atomicity guarantees must override this method and document its concurrency properties.

So you could use that default implementation. Put it in a static helper method maybe.

But if this is supposed to be thread-safe, you may need to add some synchronization code (or consider using a ConcurrentMap, which by the way already has the remove method since Java 5).

like image 99
Thilo Avatar answered Oct 13 '22 01:10

Thilo


The remove(key, value) method removes the entry for key if it is currently mapped to value. The method was added in Java 1.8. The Javadoc for the Map interface mentions the following default implementation:

if (map.containsKey(key) && Objects.equals(map.get(key), value)) {
     map.put(key, newValue);
     return true;
} else
     return false;

Since the Objects class was only added in Java 1.7, for Java 1.6 you have to write the equality test yourself. So, if you don't need the return value of the method, you can replace map.remove(key, value) with:

if (map.containsKey(key) {
    Object storedValue = map.get(key);
    if (storedValue == null ? value == null : storedValue.equals(value)) {
        map.remove(key);
    }
}

Note that this is not thread-safe. If you access the map from multiple threads, you will have to add a synchronized block.

like image 27
Hoopje Avatar answered Oct 12 '22 23:10

Hoopje


You'll have to test the value yourself:

if(fruitProperties.equals(fruitMap.get(fruitId)) {
    fruitMap.remove(fruitId);
}

Note, my implementation here assumes you are testing a non-null fruitProperties object.

like image 20
Todd Avatar answered Oct 13 '22 00:10

Todd


You need to do the following assuming your values cannot be null

if (fruitProperties.equals(fruitMap.get(fruitId))
    fruitMap.remove(fruitId);

Note: for this to be thread safe you would need to wrap this in a synchronized block.

like image 29
Peter Lawrey Avatar answered Oct 12 '22 23:10

Peter Lawrey