Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HashMap<String, boolean> copy all the keys into HashMap<String, Integer>and initialize values to zero

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.

like image 226
NimChimpsky Avatar asked Nov 11 '10 15:11

NimChimpsky


3 Answers

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)));
like image 196
ColinD Avatar answered Nov 14 '22 22:11

ColinD


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.

like image 29
Todd Avatar answered Nov 14 '22 21:11

Todd


final Integer ZERO = 0;

for(String s : input.keySet()){
   output.put(s, ZERO);
}
like image 25
pgras Avatar answered Nov 14 '22 20:11

pgras