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.
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)));
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.
final Integer ZERO = 0;
for(String s : input.keySet()){
output.put(s, ZERO);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With