什么是最好的方法?
只是遍历并放置键和零,或者是否有另一种更优雅或现有的库方法。如果 Google 的 guava java 库有任何有用的功能,我也在使用它吗?
想检查是否有类似于列表复制方法或 Map 的 putAll 的方法方法,但仅用于键。
最佳答案
不要认为这里需要什么花哨的东西:
Map<String, Boolean> map = ...;
Map<String, Integer> newMap = Maps.newHashMapWithExpectedSize(map.size());
for (String key : map.keySet()) {
newMap.put(key, 0);
}
如果你确实想要 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)));
关于java - HashMap<String, boolean> 将所有键复制到 HashMap<String, Integer> 并将值初始化为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4156306/