I have several profiles that are in form of mappings (id,value)
and I need to find average between that profiles (values). The issue is that not all profile consist of the same ids
, so that the lengths are different, as here:
1 2 3 4 5 6
-----------
1 3 - 5 - 9
0 - 1 1 2 -
The first row denotes element_id
and rows 2 and 3 denote the user profiles. '-' is the element with no value. The average for these 2 profiles is: {0.5, 3, 1, 3, 2, 9}
.
I have implemented is as following:
private static void calcAverage(Map<Integer, Map<Integer, Integer>> profiles) {
Map<Integer, Float> res = new HashMap<>();
Map<Integer, Integer> elemcount = new HashMap<>();
Map<Integer, Integer> elemsums = new HashMap<>();
for (Map<Integer, Integer> profile : profiles.values()) {
for (Map.Entry<Integer, Integer> element : profile.entrySet()) {
if (!elemcount.containsKey(element.getKey())) {
elemcount.put(element.getKey(), 1);
elemsums.put(element.getKey(), element.getValue());
} else {
int count = elemcount.get(element.getKey());
elemcount.put(element.getKey(), count + 1);
int sum = elemsums.get(element.getKey());
elemsums.put(element.getKey(), element.getValue() + sum);
}
}
}
for (Map.Entry<Integer, Integer> entry : elemcount.entrySet()) {
System.out.println(entry.getKey() + " => " + (double)elemsums.get(entry.getKey())/(double)entry.getValue());
}
}
The source is working perfectly. It does what I want.
The only thing, I wanted to ask, if it is possible to optimize it somehow? Because when I have 1k profiles with 1k elements each, it will take really much time to work on.
p1={1->1, 2->3, 4->5, 6->9}
andp2={1->0, 3->1, 4->1,5->2}
then the average is{1->0.5, 2->3, 3->1, 4->3, 5->2, 6->9}
. \$\endgroup\$