Summing absolute values of HashMap java

Viewed 205

How do I convert the double values to a positive number before summing this map. In other words, trying to get the sum of absolute values before obtaining total.

Map<String,Double> map = new HashMap<>();
map.put("CAT",-9.3);
map.put("BYTE", 15.6);
map.put("JOB", -11.66);
map.put("VIS", 8.0);


double TotalAbs = map.values().stream()
                         .mapToDouble(w -> w)
                         .sum();

Trying to sum the absolute value of the doubles ==> The answer should be 44.56 and not 2.64.
Please click here for IMAGE from Excel Please help out. Thanks.

2 Answers

You can try Math.abs. It will convert the negative numbers to positive.

double totalAbs = map.values().stream()
                             .mapToDouble(w -> Math.abs(w))
                             .sum();

loop

double sum = 0;

for (Double val : map.values())
    sum += Math.abs(val);

stream

double sum = map.values().stream().map(Math::abs).reduce(Double::sum).orElse(0.0);

result:

System.out.println(sum); // 44.56
Related