Reputation: 793
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});
Upvotes: 0
Views: 9147
Reputation: 31339
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 (see the Oracle tutorial, The Conditional Operators part):
myHashMap.put(key, condition ? value : otherValue);
Upvotes: 4
Reputation: 11483
Just to tack on to Reut's answer, if you're wanting to operate on a value already in the map, there's Map#compute as of Java 8:
Map<String, String> example = new HashMap<>();
//pretending we have values...
example.compute("My Key", (key, oldValue) -> oldValue == null ? "New" : "Read");
Upvotes: 3
Reputation: 23042
Not exactly, you would have to do something like:
// Assuming a boolean value is returned
if (myHashMap.get(key)) {
myHashMap.put(key, value);
} else {
myHashMap.put(key, differentValue);
}
Upvotes: 1