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

寵の児 提交于 2019-12-13 12:27:40

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!