hello_its_me hello_its_me - 5 months ago 16
Java Question

Add value to key only with condition for hashmap

Is there any way I could add a value (or change a key's value) to a key only if a condition is met?

I mean, something like:

myHashMap.add(key, if(true){//add this value} else {//add a different value});


Yes, use if-else:

if (condition){
    myHashMap.put(key, value);
} else {
    myHashMap.put(key, otherValue);

If you insist on making it short use the ternary operator:

myHashMap.put(key, condition ? value : otherValue);