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

Nim*_*sky 6 java hashmap guava

什么是最好的方法 ?

只需循环并放置键和零,或者是另一个更优雅或现有的库方法.如果它有任何有用的功能,我也使用谷歌的guava java库?

想要检查是否有类似于列表的复制方法或Map的putAll方法,但仅用于键.

Col*_*inD 20

不要认为这里有任何想象的东西:

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

如果您确实想要与番石榴一样的东西,有这个选项:

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)));
Run Code Online (Sandbox Code Playgroud)