Average of multiple vectors with different length 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&lt;Integer, Map&lt;Integer, Integer&gt;&gt; profiles) {
        Map&lt;Integer, Float&gt; res = new HashMap&lt;&gt;();
        Map&lt;Integer, Integer&gt; elemcount = new HashMap&lt;&gt;();
        Map&lt;Integer, Integer&gt; elemsums = new HashMap&lt;&gt;();

        for (Map&lt;Integer, Integer&gt; profile : profiles.values()) {
            for (Map.Entry&lt;Integer, Integer&gt; 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&lt;Integer, Integer&gt; entry : elemcount.entrySet()) {
            System.out.println(entry.getKey() + " =&gt; " + (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.
Your code is O(NM) because it iterates through every value, for every id. 

You need to iterate through the values once, adding the values to some structure which tracks the sum of every value for every id, and the number of values seen.

This lets you calculate average = (sum_values)/n_values in O(N+M), where N is number of values, M is number of ids.