Java HashMap<String, boolean> 将所有键复制到 HashMap<String, Integer> 并将值初始化为零

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4156306/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 12:08:00  来源:igfitidea点击:

HashMap<String, boolean> copy all the keys into HashMap<String, Integer>and initialize values to zero

javahashmapguava

提问by NimChimpsky

What is the best way ?

什么是最好的方法 ?

Just looping through and putting the key and zero, or is there another more elegant or existing library method. I am also using Google's guava java library if that has any useful functionality ?

只需循环并输入键和零,或者是否有另一种更优雅或现有的库方法。如果有任何有用的功能,我也在使用 Google 的 guava java 库吗?

Wanted to check if there was anything similar to the copy method for lists, or Map's putAllmethod, but just for keys.

想检查是否有类似于列表的 copy 方法或 Map 的putAll方法,但仅适用于键。

采纳答案by ColinD

Don't think there's much need for anything fancy here:

不要认为这里不需要任何花哨的东西:

Map<String, Boolean> map = ...;
Map<String, Integer> newMap = Maps.newHashMapWithExpectedSize(map.size());
for (String key : map.keySet()) {
  newMap.put(key, 0);
}

If you do want something fancy with Guava, there is this option:

如果您确实想要 Guava 的一些奇特之处,可以使用以下选项:

Map<String, Integer> newMap = Maps.newHashMap(
    Maps.transformValues(map, Functions.constant(0)));

// 1-liner with static imports!
Map<String, Integer> newMap = newHashMap(transformValues(map, constant(0)));

回答by pgras

final Integer ZERO = 0;

for(String s : input.keySet()){
   output.put(s, ZERO);
}

回答by Todd

Looping is pretty easy (and not inelegant). Iterate over the keys of the original Mapand put it in them in the new copy with a value of zero.

循环非常简单(而且不优雅)。迭代原始键Map并将其放入新副本中,值为 0。

Set<String> keys = original.keySet();
Map<String, Integer> copy = new HashMap<String, Integer>();
for(String key : keys) {
    copy.put(key, 0);
}

Hope that helps.

希望有帮助。