hello_its_me hello_its_me - 4 months ago 13
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});

Answer

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);
Comments