问题
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 ?
Wanted to check if there was anything similar to the copy method for lists, or Map's putAll method, but just for keys.
回答1:
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)));
回答2:
Looping is pretty easy (and not inelegant). Iterate over the keys of the original Map and put it in them in the new copy with a value of zero.
Set<String> keys = original.keySet();
Map<String, Integer> copy = new HashMap<String, Integer>();
for(String key : keys) {
copy.put(key, 0);
}
Hope that helps.
回答3:
final Integer ZERO = 0;
for(String s : input.keySet()){
output.put(s, ZERO);
}
来源:https://stackoverflow.com/questions/4156306/hashmapstring-boolean-copy-all-the-keys-into-hashmapstring-integerand-init