本文介绍了在 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