[英]In Java8 functional style, how can i map the values to already existing key value pair
I have a map:我有一张地图:
Map<String, List<Object>> dataMap;
Now i want to add new key value pairs to the map like below:现在我想向地图添加新的键值对,如下所示:
if(dataMap.contains(key)) {
List<Object> list = dataMap.get(key);
list.add(someNewObject);
dataMap.put(key, list);
} else {
List<Object> list = new ArrayList();
list.add(someNewObject)
dataMap.put(key, list);
}
How can i do this with Java8 functional style?我怎样才能用 Java8 功能风格做到这一点?
You can use computeIfAbsent
.您可以使用computeIfAbsent
。
If the mapping is not present, just create one by associating the key with a new empty list, and then add the value into it.如果映射不存在,只需通过将键与新的空列表相关联来创建一个,然后将值添加到其中。
dataMap.computeIfAbsent(key, k -> new ArrayList<>()).add(someNewObject);
As the documentation states, it returns the current (existing or computed) value associated with the specified key so you can chain the call with ArrayList#add
.正如文档所述,它返回与指定键关联的当前(现有或计算出的)值,以便您可以使用ArrayList#add
链接调用。 Of course this assume that the values in the original map are not fixed-size lists (I don't know how you filled it)...当然这假设原始地图中的值不是固定大小的列表(我不知道你是如何填充它的)......
By the way, if you have access to the original data source, I would grab the stream from it and use Collectors.groupingBy
directly.顺便说一句,如果您可以访问原始数据源,我会从中获取流并直接使用Collectors.groupingBy
。
This can be simplified by using the ternary operator.这可以通过使用三元运算符来简化。 You don't really need the if-else statement你真的不需要 if-else 语句
List<Object> list = dataMap.containsKey(key) ? dataMap.get(key) : new ArrayList<>();
list.add(someNewObject);
dataMap.put(key, list);
You can also use compute
method.您也可以使用compute
方法。
dataMap.compute(key, (k, v) -> {
if(v == null)
return new ArrayList<>();
else {
v.add(someNewObject);
return v;
}
});
you can use您可以使用
dataMap.compute(key,(k,v)->v!=null?v:new ArrayList<>()).add(someNewObject)
or或者
dataMap.merge(key,new ArrayList<>(),(v1,v2)->v1!=null?v1:v2).add(someNewObject)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.