putIfAbsent() + replace()
You can use a combination Map.putIfAbsent()
+ three-args version of Map.replace()
:
attributes.putIfAbsent("id", systemGeneratedDetails.get(0).getId());
attributes.replace("id", "", systemGeneratedDetails.get(0).getId());
To avoid code-repetition, this logic can be extracted into a separate method and gentrified:
public static <K, V> void putIfNullOrEmpty(Map<K, V> map,
K key, V oldValue, V newValue) {
map.putIfAbsent(key, newValue);
map.replace(key, oldValue, newValue);
}
Usage example:
putIfNullOrEmpty(attributes, "id", "", systemGeneratedDetails.get(0).getId());
putIfNullOrEmpty(attributes, "Name", "", systemGeneratedDetails.get(0).getId());
compute()
Another way to achieve that is by using Java 8 method Map.compute()
, which expects a key and a remappingFunction responsible for generating the resulting value based on the key and existing value associated with the key:
attributes.compute("Id", (k, v) -> v == null || v.isEmpty() ?
systemGeneratedDetails.get(0).getId() : v);
To avoid redundancy, you can extract this logic into a separate method and gentrify it:
public static <K, V> void putIf(Map<K, V> map,
Predicate<V> condition,
K key, V newValue) {
map.compute(key, (k, v) -> condition.test(v) ? newValue : v);
}
Usage example:
Predicate<String> isNullOrEmpty = v -> v == null || v.isEmpty();
putIf(attributes, isNullOrEmpty, "id", systemGeneratedDetails.get(0).getId());
putIf(attributes, isNullOrEmpty, "Name", systemGeneratedDetails.get(0).getId());