In my Spring Boot application I have two Maps:
Map<String, String> defaultValuesMap = Map.of(
"BMW", "Something",
"Audi", "Something else",
"Nissan", "Something else"
);
Map<String, String> myMap = Map.of(
"Mercedes", "Something",
"Suzuki", "Whatever",
"Audi", "Dummy data",
"Nissan", ""
);
I’m trying to make some logic that takes alle the Entries in defaultValuesMap and say if that entry does not exist in myMap OR it exists but the value is blank, then replace that key/value pair with the one from defaultValuesMap.
The result would look like this:
Map<String, String> myMap = Map.of(
"Mercedes", "Something",
"Suzuki", "Whatever",
"Audi", "Dummy data",
"Nissan", "Something else",
"BMW", "Something"
);
I’ve tried something like this:
defaultValuesMap.entrySet()
.stream()
.map(entry -> {
if (!myMap.containsKey(entry) || myMap.get(entry).isBlank)
myMap.put(
entry.getKey(),
entry.getValue());
return entry;
});
This didn’t work, then I tried to add collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); to the end of it but then it just replaced the elements even if they were not missing or blank…
>Solution :
Map.of returns an unmodifiable map, which as the name implies cannot be modified. Create a third result map or if you want to do it in place like in your example, make the second map modifiable. Then you can use map.compute to get the desired result:
Map<String, String> defaultValuesMap = Map.of(
"BMW", "Something",
"Audi", "Something else",
"Nissan", "Something else");
Map<String, String> myMap = new HashMap<>(Map.of(
"Mercedes", "Something",
"Suzuki", "Whatever",
"Audi", "Dummy data",
"Nissan", ""));
defaultValuesMap.forEach((k,v) ->{
myMap.compute(k, (k1, prev) -> prev == null || prev.isBlank() ? v : prev);
});
System.out.println(myMap);