本文介绍了HashMap< String,boolean>将所有键复制到HashMap< String,Integer>并将值初始化为零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么是最好的方法?
仅循环遍历并放置密钥和零,或者是否存在另一个更优雅的或现有的库方法.我是否还在使用Google的番石榴Java库,如果它具有任何有用的功能?
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 ?
想检查是否有类似于列表的复制方法的内容,或Map的 putAll 方法,但仅用于键.
Wanted to check if there was anything similar to the copy method for lists, or Map's putAll method, but just for keys.
推荐答案
不要以为这里有什么花哨的东西:
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:
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)));
这篇关于HashMap< String,boolean>将所有键复制到HashMap< String,Integer>并将值初始化为零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!