'transform map : add new key value pairs to existing map Java 8

I'm trying to transform a Map by adding a new JsonObject key-value pair, if any of the map's JsonObject's key contains the "-fragment" String.

Set<Map.Entry<String, JsonElement>> entries = rootJsonElement.getAsJsonObject().entrySet();
for (Map.Entry<String, JsonElement> entry : entries) {
    if (entry.getKey().contains("-fragment")) {
        // apply function that gets fragment data and adds
        // jsonobject 
    }
}

Could someone give me an example of how to do this in Java8?



Solution 1:[1]

You could achieve this even without java stream by simply invoking the foreach method of the Set class to traverse all its entries. Then, check if the entry's key satisfies your condition and in that case apply your Function.

Function<...> f = /* ... my function implementation ... */
entries.forEach(entry -> {
    if (entry.getKey().contains("-fragment")){
        f.apply(entry);
    }
});

Instead, if you want to use java stream to return a brand new Set created by the application of your Function, then you could stream your Set, filter each entry in the same way you're doing in your loop, map each entry to apply your Function and then return a value (the Function returning value, the updated entry or anything else you need). Finally, use the terminal operation collect to collect your data in a new Set.

Function<...> f = /* ... my function implementation ... */
Set<Map.Entry<String, JsonElement>> result = entries.stream()
        .filter(entry -> entry.getKey().contains("-fragment"))
        .map(entry -> {
            //applying your function
            f.apply(entry);
            return entry;
        })
        .collect(Collectors.toSet());

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dan