hello_its_me hello_its_me - 1 year ago 74
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 Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download