本文介绍了在Java8功能样式中,如何将值映射到已存在的键值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个地图:

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);
}

我如何使用Java8功能样式?

How can i do this with Java8 functional style?

推荐答案

您可以使用 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);

如文档所述,它返回与指定键相关联的当前(现有或计算)值,您可以使用 ArrayList#add 链接调用。当然,这假设原始地图中的值不是固定大小的列表(我不知道你如何填充它)...

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. Of course this assume that the values in the original map are not fixed-size lists (I don't know how you filled it)...

顺便说一句,如果您可以访问原始数据源,我将从中获取流,并直接使用 Collectors.groupingBy

By the way, if you have access to the original data source, I would grab the stream from it and use Collectors.groupingBy directly.

这篇关于在Java8功能样式中,如何将值映射到已存在的键值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 13:12