Little Kevin
Little Kevin

Reputation: 107

Get Average Value of Two+ HashMap using Java 8

I have two HashMap<String, Integer> How can I get the average of the values?

HashMap<String, Integer> map1 = ...
map1.put("str1", 7);
map1.put("str2", 4);

HashMap<String, Integer> map2 = ...
map2.put("str1", 3);
map2.put("str2", 2);

The expected output is:

("str1") = 5;
("str2") = 3;

I am able to retrieve the sum of two maps as follows:

map2.forEach((k, v) -> map1.merge(k, v, Integer::sum)); 

But how can I retrieve the average of two maps using Java 8?

Update:

At the request of @ I am posting a larger portion of my code:

HashMap<String, HashMap<String, Double>> map;

        HashMap<String, Double> map2 = new HashMap<String, Double>();
        map = func1(); 
        map = func2();
        map = func3();

        for (Entry<String, HashMap<String, Double>> entry : map.entrySet()) {
            String key = entry.getKey();
            HashMap<String, Double> mp = map.get(key);
            mp.forEach((k, v) -> map2.merge(k, v, (t, u) -> (t + u) / 2));

            for (Entry<String, Double> entry1 : mp.entrySet()) {

                StringfieldName = entry1.getKey();
                Double score= entry1.getValue();
                System.out.println(fieldName.toString() + " = " + score);

            }
        }
        return map2;
    }

Upvotes: 3

Views: 1381

Answers (2)

Trash Can
Trash Can

Reputation: 6814

Why not take advantage of Java 8 features altogether?

double avg = Stream.of(map1.values(), map2.values())
                   .map(set -> set.stream().collect(Collectors.summingInt(Integer::intValue)))
                   .collect(Collectors.averagingDouble(Integer::doubleValue));

Upvotes: 0

Youcef LAIDANI
Youcef LAIDANI

Reputation: 59960

Did you tried to do this :

map1.forEach((k, v) -> map1.merge(k, v, (t, u) -> (t + u) / 2));

Upvotes: 6

Related Questions