简体   繁体   English

如何在java中为Map中的特定键增加值?

[英]How to increment value for a specific key in a Map in java?

In C++ if I declare a map like std::map m在 C++ 中,如果我声明一个像 std::map m 的映射

then I can increment the value for a specific key in the map in this way然后我可以通过这种方式增加地图中特定键的值

m[key]++

In Java I declare a map在 Java 中,我声明了一个地图

Map<Integer, Integer> m = new HashMap<>();

and I increment the value for a specific key in this way:我以这种方式增加特定键的值:

m.put(key, m.get(key).intValue() + 1)

My question: Is there any shortcut or better way to do this?我的问题:有没有捷径或更好的方法来做到这一点?

您可以使用计算(Java 8+):

m.compute(key, (k, v) -> v + 1);

I've always preferred to use a mutable int for these problems.对于这些问题,我一直倾向于使用可变 int So the code ends up looking like...所以代码最终看起来像......

m.get(key).increment()

This avoids the unnecessary put overhead (which is small).这避免了不必要的放置开销(很小)。

You don't need the .intValue() because of autoboxing, but apart from that, there is no better way to do this.由于自动装箱,您不需要.intValue() ,但除此之外,没有更好的方法来做到这一点。

m.put(key, m.get(key) + 1)

The reason (or the problem) is that Java decided not to let classes implement their own operators (like it is possible in C++).原因(或问题)是 Java 决定不让类实现它们自己的运算符(就像在 C++ 中是可能的)。

There is a problem with the accepted answer that if there is no value for a requested key, we'll get an exception.接受的答案存在一个问题,即如果请求的键没有值,我们将收到异常。 Here are a few ways to resolve the issue using Java 8 features:以下是使用 Java 8 功能解决问题的几种方法:

  1. Using Map.merge()使用Map.merge()

m.merge(key, 1, Integer::sum)

If the key doesn't exist, put 1 as value, otherwise sum 1 to the value given for the key.如果键不存在,则将 1 作为值,否则将 1 与为键给出的值相加。

  1. Using Map.putIfAbsent()使用Map.putIfAbsent()
m.putIfAbsent(key, 1);
m.put(key, m.get(key) + 1);

Similar to other answers, but clearly says you need to init the value first.与其他答案类似,但明确表示您需要先初始化该值。

  1. Using Map.compute()使用Map.compute()

m.compute(key, (k, v) -> v == null ? 1 : v + 1)

Always computing the value, providing 1 if there is nothing there yet.始终计算值,如果还没有任何东西,则提供 1。

  1. Using Map.getOrDefault()使用Map.getOrDefault()

m.put(key, m.getOrDefault(key, 0) + 1)

Gets the value if it exists or a default value otherwise, and returns that value plus one.获取值(如果存在)或默认值,并返回该值加一。

您可以删除intValue调用并依靠自动拆箱。

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

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