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.
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
}
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) {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With