Average of even numbers gives back wrong value












4















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?










share|improve this question




















  • 6





    Your filter is only retaining positive odd numbers.

    – khelwood
    Jan 2 at 14:28








  • 3





    your title says you want an average of even numbers and your description says the opposite. what do you want?

    – Aomine
    Jan 2 at 14:29


















4















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?










share|improve this question




















  • 6





    Your filter is only retaining positive odd numbers.

    – khelwood
    Jan 2 at 14:28








  • 3





    your title says you want an average of even numbers and your description says the opposite. what do you want?

    – Aomine
    Jan 2 at 14:29
















4












4








4








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?










share|improve this question
















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?







java lambda java-stream






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 2 at 14:33









Naman

44.9k11102204




44.9k11102204










asked Jan 2 at 14:27









Csongi NagyCsongi Nagy

19319




19319








  • 6





    Your filter is only retaining positive odd numbers.

    – khelwood
    Jan 2 at 14:28








  • 3





    your title says you want an average of even numbers and your description says the opposite. what do you want?

    – Aomine
    Jan 2 at 14:29
















  • 6





    Your filter is only retaining positive odd numbers.

    – khelwood
    Jan 2 at 14:28








  • 3





    your title says you want an average of even numbers and your description says the opposite. what do you want?

    – Aomine
    Jan 2 at 14:29










6




6





Your filter is only retaining positive odd numbers.

– khelwood
Jan 2 at 14:28







Your filter is only retaining positive odd numbers.

– khelwood
Jan 2 at 14:28






3




3





your title says you want an average of even numbers and your description says the opposite. what do you want?

– Aomine
Jan 2 at 14:29







your title says you want an average of even numbers and your description says the opposite. what do you want?

– Aomine
Jan 2 at 14:29














3 Answers
3






active

oldest

votes


















11














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





share|improve this answer































    3















    What is my code doing now?




    You're performing a modulo operation on negative number.




    How should I fix it to do what it's supposed to do?




    You can use Math.abs to validate the absolute value is odd or not in your list:



    OptionalDouble result = numbers.stream()
    .filter(i -> Math.abs(i) % 2 == 1) // verify id the absolute value is odd
    .mapToDouble(i->i).average();





    share|improve this answer





















    • 1





      Thank you so much!

      – Csongi Nagy
      Jan 2 at 15:00



















    2














    In addition to what @khelwood mentioned regarding modulo with negative numbers.



    It's important to know that, the filter intermediate operation does not remove elements nor does any stream operation, instead, filter returns a new stream in which all the elements satisfying the provided predicate i.e. i -> i % 2 == 1 are present.



    i -> i % 2 == 1 is saying "only keep the element represented as i if it's an odd number".



    if you want even then you should do i -> i % 2 == 0, reads as "only keep the element represented as i is it's an even number".





    On another note, if you're running on JDK9 you can use ifPresentOrElse to simply the isPresent() check.



     numbers.stream()
    .filter(i -> i % 2 == 0)
    .mapToDouble(i -> i)
    .average()
    .ifPresentOrElse(System.out::println,
    () -> System.out.println("Error"));





    share|improve this answer





















    • 1





      Thank you for the clear explanation!

      – Csongi Nagy
      Jan 2 at 15:01











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54008089%2faverage-of-even-numbers-gives-back-wrong-value%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    11














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





    share|improve this answer




























      11














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





      share|improve this answer


























        11












        11








        11







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





        share|improve this answer













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






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 2 at 14:30









        khelwoodkhelwood

        31.9k74465




        31.9k74465

























            3















            What is my code doing now?




            You're performing a modulo operation on negative number.




            How should I fix it to do what it's supposed to do?




            You can use Math.abs to validate the absolute value is odd or not in your list:



            OptionalDouble result = numbers.stream()
            .filter(i -> Math.abs(i) % 2 == 1) // verify id the absolute value is odd
            .mapToDouble(i->i).average();





            share|improve this answer





















            • 1





              Thank you so much!

              – Csongi Nagy
              Jan 2 at 15:00
















            3















            What is my code doing now?




            You're performing a modulo operation on negative number.




            How should I fix it to do what it's supposed to do?




            You can use Math.abs to validate the absolute value is odd or not in your list:



            OptionalDouble result = numbers.stream()
            .filter(i -> Math.abs(i) % 2 == 1) // verify id the absolute value is odd
            .mapToDouble(i->i).average();





            share|improve this answer





















            • 1





              Thank you so much!

              – Csongi Nagy
              Jan 2 at 15:00














            3












            3








            3








            What is my code doing now?




            You're performing a modulo operation on negative number.




            How should I fix it to do what it's supposed to do?




            You can use Math.abs to validate the absolute value is odd or not in your list:



            OptionalDouble result = numbers.stream()
            .filter(i -> Math.abs(i) % 2 == 1) // verify id the absolute value is odd
            .mapToDouble(i->i).average();





            share|improve this answer
















            What is my code doing now?




            You're performing a modulo operation on negative number.




            How should I fix it to do what it's supposed to do?




            You can use Math.abs to validate the absolute value is odd or not in your list:



            OptionalDouble result = numbers.stream()
            .filter(i -> Math.abs(i) % 2 == 1) // verify id the absolute value is odd
            .mapToDouble(i->i).average();






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Jan 2 at 14:46

























            answered Jan 2 at 14:32









            NamanNaman

            44.9k11102204




            44.9k11102204








            • 1





              Thank you so much!

              – Csongi Nagy
              Jan 2 at 15:00














            • 1





              Thank you so much!

              – Csongi Nagy
              Jan 2 at 15:00








            1




            1





            Thank you so much!

            – Csongi Nagy
            Jan 2 at 15:00





            Thank you so much!

            – Csongi Nagy
            Jan 2 at 15:00











            2














            In addition to what @khelwood mentioned regarding modulo with negative numbers.



            It's important to know that, the filter intermediate operation does not remove elements nor does any stream operation, instead, filter returns a new stream in which all the elements satisfying the provided predicate i.e. i -> i % 2 == 1 are present.



            i -> i % 2 == 1 is saying "only keep the element represented as i if it's an odd number".



            if you want even then you should do i -> i % 2 == 0, reads as "only keep the element represented as i is it's an even number".





            On another note, if you're running on JDK9 you can use ifPresentOrElse to simply the isPresent() check.



             numbers.stream()
            .filter(i -> i % 2 == 0)
            .mapToDouble(i -> i)
            .average()
            .ifPresentOrElse(System.out::println,
            () -> System.out.println("Error"));





            share|improve this answer





















            • 1





              Thank you for the clear explanation!

              – Csongi Nagy
              Jan 2 at 15:01
















            2














            In addition to what @khelwood mentioned regarding modulo with negative numbers.



            It's important to know that, the filter intermediate operation does not remove elements nor does any stream operation, instead, filter returns a new stream in which all the elements satisfying the provided predicate i.e. i -> i % 2 == 1 are present.



            i -> i % 2 == 1 is saying "only keep the element represented as i if it's an odd number".



            if you want even then you should do i -> i % 2 == 0, reads as "only keep the element represented as i is it's an even number".





            On another note, if you're running on JDK9 you can use ifPresentOrElse to simply the isPresent() check.



             numbers.stream()
            .filter(i -> i % 2 == 0)
            .mapToDouble(i -> i)
            .average()
            .ifPresentOrElse(System.out::println,
            () -> System.out.println("Error"));





            share|improve this answer





















            • 1





              Thank you for the clear explanation!

              – Csongi Nagy
              Jan 2 at 15:01














            2












            2








            2







            In addition to what @khelwood mentioned regarding modulo with negative numbers.



            It's important to know that, the filter intermediate operation does not remove elements nor does any stream operation, instead, filter returns a new stream in which all the elements satisfying the provided predicate i.e. i -> i % 2 == 1 are present.



            i -> i % 2 == 1 is saying "only keep the element represented as i if it's an odd number".



            if you want even then you should do i -> i % 2 == 0, reads as "only keep the element represented as i is it's an even number".





            On another note, if you're running on JDK9 you can use ifPresentOrElse to simply the isPresent() check.



             numbers.stream()
            .filter(i -> i % 2 == 0)
            .mapToDouble(i -> i)
            .average()
            .ifPresentOrElse(System.out::println,
            () -> System.out.println("Error"));





            share|improve this answer















            In addition to what @khelwood mentioned regarding modulo with negative numbers.



            It's important to know that, the filter intermediate operation does not remove elements nor does any stream operation, instead, filter returns a new stream in which all the elements satisfying the provided predicate i.e. i -> i % 2 == 1 are present.



            i -> i % 2 == 1 is saying "only keep the element represented as i if it's an odd number".



            if you want even then you should do i -> i % 2 == 0, reads as "only keep the element represented as i is it's an even number".





            On another note, if you're running on JDK9 you can use ifPresentOrElse to simply the isPresent() check.



             numbers.stream()
            .filter(i -> i % 2 == 0)
            .mapToDouble(i -> i)
            .average()
            .ifPresentOrElse(System.out::println,
            () -> System.out.println("Error"));






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Jan 2 at 15:11

























            answered Jan 2 at 14:37









            AomineAomine

            42.5k74676




            42.5k74676








            • 1





              Thank you for the clear explanation!

              – Csongi Nagy
              Jan 2 at 15:01














            • 1





              Thank you for the clear explanation!

              – Csongi Nagy
              Jan 2 at 15:01








            1




            1





            Thank you for the clear explanation!

            – Csongi Nagy
            Jan 2 at 15:01





            Thank you for the clear explanation!

            – Csongi Nagy
            Jan 2 at 15:01


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54008089%2faverage-of-even-numbers-gives-back-wrong-value%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            MongoDB - Not Authorized To Execute Command

            How to fix TextFormField cause rebuild widget in Flutter

            in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith