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 help out. Thanks.
To sum absolute values in Excel, you can use the ABS function. This function returns the absolute value of a number, which is a number without its sign. So, if a number is positive, the ABS function will return the same number. If a number is negative, the ABS function will return the positive version of that number.
abs(int a) returns the absolute value of an int value. If the argument is not negative, the argument is returned. If the argument is negative, the negation of the argument is returned.
The Java HashMap values () method returns a view of all the values present in entries of the hashmap. The syntax of the values () method is: Here, hashmap is an object of the HashMap class. The values () method does not take any parameter. The collection view only shows all values of the hashmap as one of the collection.
In Java, we can find the absolute value by using the abs () method. It belongs to java.lang.Math class. It is an overloaded method. It returns the absolute value of an argument. The argument can be of any type such as int, float, double, long, and short.
Here, first, we access the value using the HashMap get () method. In the above example, we have recomputed the value of the key Second using the computeIfPresent () method. To learn more, visit HashMap computeIfPresent (). Here, we have used the lambda expression as the method argument to the method.
In Java 8 or above, the sum operation can be done trivially using Streams without any loops. We can also perform a reduction operation on stream elements using the reduce () method. 2. Using for loop Before Java 8, we can use replace the Stream API chain with a simple for loop: That’s all about calculating the sum of all values in a Map<?,
You can try Math.abs
. It will convert the negative numbers to positive.
double totalAbs = map.values().stream()
.mapToDouble(w -> Math.abs(w))
.sum();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With