Hashmap that retains original key / value when double key is entered

Is it possible to Hashmap

keep its original pair key/value

when a duplicate key is entered?

For example, let's say I have something like this:

Map<String, String> map = new HashMap<String, String>();

map.put("username","password1");
map.put("username","password2");

      

I want the original pair key/value

- username, password1 to be saved and not reloaded by username, password2.

Is it possible? If not, how can I remove duplicate entries from the map?

+3


source to share


3 answers


As mentioned, you can use putIfAbsent

if you are using Java 8.

If you are on an older version of Java, you can use ConcurrentHashMap

instead which has a method putIfAbsent

.



Of course, you get the additional overhead of thread safety, but unless you're writing an application with very high sensitivity, this shouldn't be a concern.

+5


source


If not in Java 8, you have some options.

The simplest is verbal code everywhere

Object existingValue = map.get(key);
if(existingValue == null){
    map.put(key,newValue);
}

      

You may have a utility method for this

public <T,V> void addToMapIfAbsent(Map<T,V> map, T key, V value){
    V oldValue = map.get(key);
    if(oldValue == null){
       map.put(key,value);
    }
}

      



Or add flavor Map

and add it there.

public class MyMap<T,V> extends HashMap<T,V>{
    public void putIfNotExist(T key, V value){
        V oldValue = get(key);
        if(oldValue == null){
            put(key,value);
        }
    }
}

      

What allows you to create Map

this way

Map<String,String> map = new MyMap<>();

      

EDIT: Although, to jump to a method MyMap

, of course you need a variable Map

declared as this type. So anywhere you need an instance MyMap

instead Map

.

+2


source


0


source







All Articles