Reputation: 47300
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.
Upvotes: 6
Views: 55671
Reputation: 110104
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)));
Upvotes: 21
Reputation: 3508
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.
Upvotes: 3
Reputation: 12780
final Integer ZERO = 0;
for(String s : input.keySet()){
output.put(s, ZERO);
}
Upvotes: 1