Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I add elements from one map to another if it doesn't exist already or the value is blank?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading