Reputation: 1459
I have been wondering for a few days now, what could be the least messy approach to my problem. I have a set of 10 enum types e.g. { ZERO, ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE } and I use these enums as keys in a map
Map<MyEnumType, Integer> myMap;
Then I generate 100 or so of these maps, with the same keys but different values. What is the best practice for adding all of these maps into one? I mean adding up all the value of those 100 maps I have generated.
Upvotes: 1
Views: 1773
Reputation: 7038
Other option would be to create class specific for summing integers instead of overriding previous values. Here's an examples how it's done with anonymous class:
public class MapSummer {
private final Map<MyEnumType, Integer> sumMap = new HashMap<MyEnumType, Integer>() {
@Override
public Integer put(MyEnumType key, Integer value) {
return super.put(key, get(key) + value);
}
@Override
public Integer get(Object key) {
return super.get(key) != null ? super.get(key) : 0;
}
};
public Map<MyEnumType, Integer> sum(List<Map<MyEnumType, Integer>> mapList) {
for (Map<MyEnumType, Integer> map : mapList) {
sumMap.putAll(map);
}
return sumMap;
}
}
enum MyEnumType {
ONE, TWO, THREE, FOUR;
}
And unit test:
public class MapSummerTest {
private final MapSummer summer = new MapSummer();
@Test
public void shouldSumValuesInMap() {
final Map<MyEnumType, Integer> map1 = new HashMap<MyEnumType, Integer>() {{
put(ONE, 1);
put(TWO, 2);
}};
final Map<MyEnumType, Integer> map2 = new HashMap<MyEnumType, Integer>() {{
put(TWO, 2);
put(THREE, 3);
}};
final Map<MyEnumType, Integer> sumMap = summer.sum(Arrays.asList(map1, map2));
assertThat(sumMap.get(ONE), equalTo(1));
assertThat(sumMap.get(TWO), equalTo(4));
assertThat(sumMap.get(THREE), equalTo(3));
assertThat(sumMap.get(FOUR), equalTo(0));
}
}
Upvotes: 1
Reputation: 691755
Iterate over the enum values, and for each enum value, iterate over the maps (or vice-versa):
Map<MyEnumType, Integer> sumMap = new EnumMap<MyEnumType, Integer>(MyEnumType.class);
for (MyEnumType e : MyEnumType.values()) {
int sum = 0;
for (Map<MyEnumType, Integer> map : maps) {
sum += map.get(e); // you might want a null check here
}
sumMap.put(e, sum);
}
Upvotes: 4