Average of even numbers gives back wrong value

Csongi Nagy :

I am trying to get closer to understanding streams thus I'm doing some basic exercises. In this one, I'd like to calculate the average of the odd numbers. I wrote this algorithm to do so, but it gives back an incorrect result (8.0). I've tried to debug it but I couldn't find what it does actually.

List<Integer> numbers = Arrays.asList(1, 3, -2, -4, -7, -3, -8, 12, 19, 6, 9, 10, 14);

OptionalDouble result = numbers.stream()
                               .filter(i -> i % 2 == 1)
                               .mapToDouble(i -> i).average();
if (result.isPresent()) {
   System.out.println(result);
} else {
   System.out.println("Error");
}

What is my code doing now? How should I fix it to do what it's supposed to do?

khelwood :
(i -> i % 2 == 1)

This is only true for positive odd numbers, because in Java the % operator returns a negative number (or zero) if its first operand is negative.

If you want to retain only even numbers, it should be:

(i -> i % 2 == 0)

If you want to retain all odd numbers (positive and negative), you can use:

(i -> i % 2 != 0)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=71821&siteId=1