简体   繁体   English

转换映射:将新的键值对添加到现有映射 Java 8

[英]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 .我正在尝试通过添加新的JsonObject键值对来转换Map ,如果地图的任何JsonObject的键包含“-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?有人可以给我一个如何在 Java8 中执行此操作的示例吗?

You could achieve this even without java stream by simply invoking the foreach method of the Set class to traverse all its entries.即使没有 java 流,您也可以通过简单地调用Set类的foreach方法来遍历其所有条目来实现这一点。 Then, check if the entry's key satisfies your condition and in that case apply your Function .然后,检查条目的键是否满足您的条件,在这种情况下应用您的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).相反,如果您想使用 java 流返回由您的Function应用程序创建的全新Set ,那么您可以流式传输您的Set ,以与循环中相同的方式过滤每个条目,映射每个条目以应用您的Function ,然后返回一个值( Function返回值、更新的条目或您需要的任何其他内容)。 Finally, use the terminal operation collect to collect your data in a new Set .最后,使用终端操作collect将您的数据收集到一个新的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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM