Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to prevent hashmap or treemap from replacing the previous value

Tags:

java

how can I prevent hashmap or treemap from replacing the previous key value if already present?Also,I want to throw an exception to notify the user.

like image 283
beinghuman Avatar asked Sep 07 '13 08:09

beinghuman


2 Answers

Any such map would be violating the normal Map interface, to be honest. But if you're happy to do that, you could easily create your own Map implementation which delegates to another map, but only after checking for the presence of an existing element:

public final class NonReplacementMap<K, V> implements Map<K, V> {
    private final Map<K, V> original;

    public NonReplacementMap(Map<K, V> original) {
        this.original = original;
    }

    @Override
    public void put(K key, V value) {
        if (original.containsKey(key)) {
            // Or whatever unchecked exception you want
            throw new IllegalStateException("Key already in map");
        }
        original.put(key, value);
    }

    // etc
}
like image 138
Jon Skeet Avatar answered Sep 28 '22 09:09

Jon Skeet


Use myMap.putIfAbsent(key, val)

This has been introduced in the Map interface since 1.8

     * @since 1.8
     */
     default V putIfAbsent(K key, V value) {
like image 41
justAnotherGuy Avatar answered Sep 28 '22 09:09

justAnotherGuy