Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Average of even numbers gives back wrong value

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?

like image 657
lyancsie Avatar asked Dec 04 '22 19:12

lyancsie


1 Answers

(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)
like image 106
khelwood Avatar answered Dec 25 '22 13:12

khelwood