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?
(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)
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