如果不存在,则将新值放入Map中,如果不存在则添加它

编程入门 行业动态 更新时间:2024-10-22 11:22:14
本文介绍了如果不存在,则将新值放入Map中,如果不存在则添加它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

对于键类型 Foo ,我有 java.util.Map< Foo,Double> 。让我们调用地图的实例 map 。

I have a java.util.Map<Foo, Double> for a key-type class Foo. Let's call the instance of the map map.

我想添加{ foo , f }( foo 是 Foo的实例和 f a Double )。但是如果键 foo 已经存在,我想将 f 加到该地图中的当前值。

I want to add {foo, f} (foo is an instance of Foo, and f a Double) to that map. But if the key foo is already present I want to sum f to the current value in that map.

目前我使用

Double current = map.get(foo); f += current == null ? 0.0 : current; map.put(foo, f);

但在Java 8中是否有一种时髦的方法,例如使用 Map#merge , Double :: sum ?

But is there a funky way of doing this in Java 8, such as using Map#merge, and Double::sum?

很遗憾,我可以'弄明白。

Regrettably I can't figure it out.

谢谢。

推荐答案

这是地图上的合并功能是什么。

this is what the merge function on maps is for.

map.merge(foo, f, (f1, f2) -> f1 + f2)

这可以进一步减少到

map.merge(foo, f, Double::sum)

它基本上是相当于

if(map.contains(foo)){ double x = map.get(foo); map.put(foo, x + f) } else { map.put(foo, f) }

更多推荐

如果不存在,则将新值放入Map中,如果不存在则添加它

本文发布于:2023-10-18 10:55:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1504028.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不存在   则将   放入   Map

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!