Reputation: 3111
I have written a method that takes a name of some field and if it's an essential field, the value is calculated for the field and is put into the map for the key.
private final Map<String, Object> valuesMap = new HashMap<>();
private void saveValues(String name) {
if (dataStore.isEssentialField(name)) {
valuesMap.put(name, calculateValue(name));
}
}
Now I want to achieve the following: if there is already a value associated with the name
key or the key is not an "essential field", the method must return the existing value and not calculate anything.
I suppose it may be achieved with computeIfAbsent
method of a Map
interface but not sure how to implement this correctly. How should the Function be implemented in this case?
private Object saveValues(String name) {
if (dataStore.isEssentialField(name)) {
Object newValue = valuesMap.computeIfAbsent(name, -> (Function<? super String, ?>) calculateValue(name));
}
return ... ? // How can the existing value be returned here?
}
Upvotes: 0
Views: 1514
Reputation: 5841
You can use a Lambda function as follows:
private Object saveValues(String name) {
if (dataStore.isEssentialField(name)) {
return valuesMap.computeIfAbsent(name, this::calculateValue);
}
return valuesMap.get(name);
}
The more classical approach would be:
private Object saveValues(String name) {
Object storedValue = valuesMap.get(name);
if (dataStore.isEssentialField(name)) {
if (storedValue != null) {
return storedValue;
}
storedValue = calculateValue(name);
valuesMap.put(name, storedValue);
}
return storedValue;
}
Upvotes: 4