user2456977
user2456977

Reputation: 3964

Hashmap that keeps original key/value when duplicate key entered

Is it possible for a Hashmap to keep its original key/value pair 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 key/value pair - username, password1 to be kept and not be overrode by username, password2.

Is this possible? If not, how can I eliminate duplicate entries from being put into the map?

Upvotes: 3

Views: 779

Answers (3)

MadConan
MadConan

Reputation: 3767

If not on Java 8, you have some options.

The most straightforward is the verbose code everywhere

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

You could have a utility method to do this for you

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 extend a flavor of 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);
        }
    }
}

Which allows you to create a Map thusly

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

EDIT: Although, to get to the MyMap method, of course, you'll need to have the map variable declared as that type. So anywhere you need that, you'll have to take an instance of MyMap instead of Map.

Upvotes: 2

K Erlandsson
K Erlandsson

Reputation: 13696

As mentioned, you can use putIfAbsent if you use Java 8.

If you are on an older Java version you can use a ConcurrentHashMap instead, which has a putIfAbsent method.

Of course, you get the additional overhead of thread safety, but if you are not writing an extremely performance sensitive application it should not be a concern.

Upvotes: 5

bcam909
bcam909

Reputation: 168

https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#putIfAbsent-K-V-

If you are using Java 8, you can use putIfAbsent.

Upvotes: 0

Related Questions