What is wrong in my approach to create a List of Integers using IntStream and forEach?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
6
down vote

favorite
1












The naive code I have is:



class $
public static void main(String _)
final List<Integer> ints = new ArrayList<>();
IntStream.iterate(0, i -> i++).limit(5).forEach(val -> ints.add(val));
System.out.println(ints);




where my expectation was to see the following in the console:



[0, 1, 2, 3, 4] 


but the actual is:



[0, 0, 0, 0, 0]


Probably something very simple but what am I missing?










share|improve this question

























    up vote
    6
    down vote

    favorite
    1












    The naive code I have is:



    class $
    public static void main(String _)
    final List<Integer> ints = new ArrayList<>();
    IntStream.iterate(0, i -> i++).limit(5).forEach(val -> ints.add(val));
    System.out.println(ints);




    where my expectation was to see the following in the console:



    [0, 1, 2, 3, 4] 


    but the actual is:



    [0, 0, 0, 0, 0]


    Probably something very simple but what am I missing?










    share|improve this question























      up vote
      6
      down vote

      favorite
      1









      up vote
      6
      down vote

      favorite
      1






      1





      The naive code I have is:



      class $
      public static void main(String _)
      final List<Integer> ints = new ArrayList<>();
      IntStream.iterate(0, i -> i++).limit(5).forEach(val -> ints.add(val));
      System.out.println(ints);




      where my expectation was to see the following in the console:



      [0, 1, 2, 3, 4] 


      but the actual is:



      [0, 0, 0, 0, 0]


      Probably something very simple but what am I missing?










      share|improve this question













      The naive code I have is:



      class $
      public static void main(String _)
      final List<Integer> ints = new ArrayList<>();
      IntStream.iterate(0, i -> i++).limit(5).forEach(val -> ints.add(val));
      System.out.println(ints);




      where my expectation was to see the following in the console:



      [0, 1, 2, 3, 4] 


      but the actual is:



      [0, 0, 0, 0, 0]


      Probably something very simple but what am I missing?







      java java-8 java-stream






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 4 hours ago









      Koray Tugay

      8,04526108210




      8,04526108210






















          4 Answers
          4






          active

          oldest

          votes

















          up vote
          4
          down vote



          accepted










          You need to return the incremented value. You postfix incremented a local variable and returned the non-incremented value. Use ++i not i++



          final List<Integer> ints = new ArrayList<>();
          IntStream.iterate(0, i -> ++i).limit(5).forEach(val -> ints.add(val));
          System.out.println(ints);





          share|improve this answer



























            up vote
            8
            down vote













            i++ has the value of i before it's incremented. You need to use the prefix operator.



            IntStream.iterate(0, i -> ++i).limit(5).forEach(val -> ints.add(val));


            Actually, don't do that. There's no reason to mutate i, it's simply thrown away. Use the side effect free version. That's the whole idea behind functional programming, after all: avoiding side effects.



            IntStream.iterate(0, i -> i + 1).limit(5).forEach(val -> ints.add(val));


            It would also be better to collect the stream into a list rather than adding values with forEach. It directly expresses the intention to create a list and again avoids side effects.



            final List<Integer> ints = IntStream.iterate(0, i -> i + 1).limit(5)
            .boxed().collect(Collectors.toList());





            share|improve this answer





























              up vote
              2
              down vote













              You are using a postfix i++, instead of a prefix ++i while passing on the value to forEach. Changing to the following shall provide you the expected output :



              IntStream.iterate(0, i -> ++i).limit(5).forEach(ints::add);


              Aside, an alternate way of iterating and combining limit with Java9+ is using IntStream.iterate with an IntPredicate as :



              IntStream.iterate(0, i -> i < 5, i -> i + 1).forEach(ints::add);





              share|improve this answer





























                up vote
                1
                down vote













                You could use a print to see what was happend:



                final List<Integer> ints = new ArrayList<>();
                IntStream.iterate(0, i ->
                System.out.println(i);
                return i++;
                ).limit(5)
                .forEach(val -> ints.add(val));
                System.out.println(ints);


                In that case, the value of i always will be 0, because the increment occurs after the value is returned, the correct way is



                final List<Integer> ints = new ArrayList<>();
                IntStream.iterate(0, i ->
                System.out.println(i);
                return ++i;
                ).limit(5)
                .forEach(val -> ints.add(val));
                System.out.println(ints);





                share|improve this answer




















                  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',
                  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%2f53182741%2fwhat-is-wrong-in-my-approach-to-create-a-list-of-integers-using-intstream-and-fo%23new-answer', 'question_page');

                  );

                  Post as a guest






























                  4 Answers
                  4






                  active

                  oldest

                  votes








                  4 Answers
                  4






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes








                  up vote
                  4
                  down vote



                  accepted










                  You need to return the incremented value. You postfix incremented a local variable and returned the non-incremented value. Use ++i not i++



                  final List<Integer> ints = new ArrayList<>();
                  IntStream.iterate(0, i -> ++i).limit(5).forEach(val -> ints.add(val));
                  System.out.println(ints);





                  share|improve this answer
























                    up vote
                    4
                    down vote



                    accepted










                    You need to return the incremented value. You postfix incremented a local variable and returned the non-incremented value. Use ++i not i++



                    final List<Integer> ints = new ArrayList<>();
                    IntStream.iterate(0, i -> ++i).limit(5).forEach(val -> ints.add(val));
                    System.out.println(ints);





                    share|improve this answer






















                      up vote
                      4
                      down vote



                      accepted







                      up vote
                      4
                      down vote



                      accepted






                      You need to return the incremented value. You postfix incremented a local variable and returned the non-incremented value. Use ++i not i++



                      final List<Integer> ints = new ArrayList<>();
                      IntStream.iterate(0, i -> ++i).limit(5).forEach(val -> ints.add(val));
                      System.out.println(ints);





                      share|improve this answer












                      You need to return the incremented value. You postfix incremented a local variable and returned the non-incremented value. Use ++i not i++



                      final List<Integer> ints = new ArrayList<>();
                      IntStream.iterate(0, i -> ++i).limit(5).forEach(val -> ints.add(val));
                      System.out.println(ints);






                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered 4 hours ago









                      flakes

                      5,80611848




                      5,80611848






















                          up vote
                          8
                          down vote













                          i++ has the value of i before it's incremented. You need to use the prefix operator.



                          IntStream.iterate(0, i -> ++i).limit(5).forEach(val -> ints.add(val));


                          Actually, don't do that. There's no reason to mutate i, it's simply thrown away. Use the side effect free version. That's the whole idea behind functional programming, after all: avoiding side effects.



                          IntStream.iterate(0, i -> i + 1).limit(5).forEach(val -> ints.add(val));


                          It would also be better to collect the stream into a list rather than adding values with forEach. It directly expresses the intention to create a list and again avoids side effects.



                          final List<Integer> ints = IntStream.iterate(0, i -> i + 1).limit(5)
                          .boxed().collect(Collectors.toList());





                          share|improve this answer


























                            up vote
                            8
                            down vote













                            i++ has the value of i before it's incremented. You need to use the prefix operator.



                            IntStream.iterate(0, i -> ++i).limit(5).forEach(val -> ints.add(val));


                            Actually, don't do that. There's no reason to mutate i, it's simply thrown away. Use the side effect free version. That's the whole idea behind functional programming, after all: avoiding side effects.



                            IntStream.iterate(0, i -> i + 1).limit(5).forEach(val -> ints.add(val));


                            It would also be better to collect the stream into a list rather than adding values with forEach. It directly expresses the intention to create a list and again avoids side effects.



                            final List<Integer> ints = IntStream.iterate(0, i -> i + 1).limit(5)
                            .boxed().collect(Collectors.toList());





                            share|improve this answer
























                              up vote
                              8
                              down vote










                              up vote
                              8
                              down vote









                              i++ has the value of i before it's incremented. You need to use the prefix operator.



                              IntStream.iterate(0, i -> ++i).limit(5).forEach(val -> ints.add(val));


                              Actually, don't do that. There's no reason to mutate i, it's simply thrown away. Use the side effect free version. That's the whole idea behind functional programming, after all: avoiding side effects.



                              IntStream.iterate(0, i -> i + 1).limit(5).forEach(val -> ints.add(val));


                              It would also be better to collect the stream into a list rather than adding values with forEach. It directly expresses the intention to create a list and again avoids side effects.



                              final List<Integer> ints = IntStream.iterate(0, i -> i + 1).limit(5)
                              .boxed().collect(Collectors.toList());





                              share|improve this answer














                              i++ has the value of i before it's incremented. You need to use the prefix operator.



                              IntStream.iterate(0, i -> ++i).limit(5).forEach(val -> ints.add(val));


                              Actually, don't do that. There's no reason to mutate i, it's simply thrown away. Use the side effect free version. That's the whole idea behind functional programming, after all: avoiding side effects.



                              IntStream.iterate(0, i -> i + 1).limit(5).forEach(val -> ints.add(val));


                              It would also be better to collect the stream into a list rather than adding values with forEach. It directly expresses the intention to create a list and again avoids side effects.



                              final List<Integer> ints = IntStream.iterate(0, i -> i + 1).limit(5)
                              .boxed().collect(Collectors.toList());






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited 4 hours ago

























                              answered 4 hours ago









                              John Kugelman

                              236k51394447




                              236k51394447




















                                  up vote
                                  2
                                  down vote













                                  You are using a postfix i++, instead of a prefix ++i while passing on the value to forEach. Changing to the following shall provide you the expected output :



                                  IntStream.iterate(0, i -> ++i).limit(5).forEach(ints::add);


                                  Aside, an alternate way of iterating and combining limit with Java9+ is using IntStream.iterate with an IntPredicate as :



                                  IntStream.iterate(0, i -> i < 5, i -> i + 1).forEach(ints::add);





                                  share|improve this answer


























                                    up vote
                                    2
                                    down vote













                                    You are using a postfix i++, instead of a prefix ++i while passing on the value to forEach. Changing to the following shall provide you the expected output :



                                    IntStream.iterate(0, i -> ++i).limit(5).forEach(ints::add);


                                    Aside, an alternate way of iterating and combining limit with Java9+ is using IntStream.iterate with an IntPredicate as :



                                    IntStream.iterate(0, i -> i < 5, i -> i + 1).forEach(ints::add);





                                    share|improve this answer
























                                      up vote
                                      2
                                      down vote










                                      up vote
                                      2
                                      down vote









                                      You are using a postfix i++, instead of a prefix ++i while passing on the value to forEach. Changing to the following shall provide you the expected output :



                                      IntStream.iterate(0, i -> ++i).limit(5).forEach(ints::add);


                                      Aside, an alternate way of iterating and combining limit with Java9+ is using IntStream.iterate with an IntPredicate as :



                                      IntStream.iterate(0, i -> i < 5, i -> i + 1).forEach(ints::add);





                                      share|improve this answer














                                      You are using a postfix i++, instead of a prefix ++i while passing on the value to forEach. Changing to the following shall provide you the expected output :



                                      IntStream.iterate(0, i -> ++i).limit(5).forEach(ints::add);


                                      Aside, an alternate way of iterating and combining limit with Java9+ is using IntStream.iterate with an IntPredicate as :



                                      IntStream.iterate(0, i -> i < 5, i -> i + 1).forEach(ints::add);






                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited 4 hours ago

























                                      answered 4 hours ago









                                      nullpointer

                                      33.7k1068136




                                      33.7k1068136




















                                          up vote
                                          1
                                          down vote













                                          You could use a print to see what was happend:



                                          final List<Integer> ints = new ArrayList<>();
                                          IntStream.iterate(0, i ->
                                          System.out.println(i);
                                          return i++;
                                          ).limit(5)
                                          .forEach(val -> ints.add(val));
                                          System.out.println(ints);


                                          In that case, the value of i always will be 0, because the increment occurs after the value is returned, the correct way is



                                          final List<Integer> ints = new ArrayList<>();
                                          IntStream.iterate(0, i ->
                                          System.out.println(i);
                                          return ++i;
                                          ).limit(5)
                                          .forEach(val -> ints.add(val));
                                          System.out.println(ints);





                                          share|improve this answer
























                                            up vote
                                            1
                                            down vote













                                            You could use a print to see what was happend:



                                            final List<Integer> ints = new ArrayList<>();
                                            IntStream.iterate(0, i ->
                                            System.out.println(i);
                                            return i++;
                                            ).limit(5)
                                            .forEach(val -> ints.add(val));
                                            System.out.println(ints);


                                            In that case, the value of i always will be 0, because the increment occurs after the value is returned, the correct way is



                                            final List<Integer> ints = new ArrayList<>();
                                            IntStream.iterate(0, i ->
                                            System.out.println(i);
                                            return ++i;
                                            ).limit(5)
                                            .forEach(val -> ints.add(val));
                                            System.out.println(ints);





                                            share|improve this answer






















                                              up vote
                                              1
                                              down vote










                                              up vote
                                              1
                                              down vote









                                              You could use a print to see what was happend:



                                              final List<Integer> ints = new ArrayList<>();
                                              IntStream.iterate(0, i ->
                                              System.out.println(i);
                                              return i++;
                                              ).limit(5)
                                              .forEach(val -> ints.add(val));
                                              System.out.println(ints);


                                              In that case, the value of i always will be 0, because the increment occurs after the value is returned, the correct way is



                                              final List<Integer> ints = new ArrayList<>();
                                              IntStream.iterate(0, i ->
                                              System.out.println(i);
                                              return ++i;
                                              ).limit(5)
                                              .forEach(val -> ints.add(val));
                                              System.out.println(ints);





                                              share|improve this answer












                                              You could use a print to see what was happend:



                                              final List<Integer> ints = new ArrayList<>();
                                              IntStream.iterate(0, i ->
                                              System.out.println(i);
                                              return i++;
                                              ).limit(5)
                                              .forEach(val -> ints.add(val));
                                              System.out.println(ints);


                                              In that case, the value of i always will be 0, because the increment occurs after the value is returned, the correct way is



                                              final List<Integer> ints = new ArrayList<>();
                                              IntStream.iterate(0, i ->
                                              System.out.println(i);
                                              return ++i;
                                              ).limit(5)
                                              .forEach(val -> ints.add(val));
                                              System.out.println(ints);






                                              share|improve this answer












                                              share|improve this answer



                                              share|improve this answer










                                              answered 4 hours ago









                                              Damian Lattenero

                                              8,86821642




                                              8,86821642



























                                                   

                                                  draft saved


                                                  draft discarded















































                                                   


                                                  draft saved


                                                  draft discarded














                                                  StackExchange.ready(
                                                  function ()
                                                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53182741%2fwhat-is-wrong-in-my-approach-to-create-a-list-of-integers-using-intstream-and-fo%23new-answer', 'question_page');

                                                  );

                                                  Post as a guest













































































                                                  Comments

                                                  Popular posts from this blog

                                                  What does second last employer means? [closed]

                                                  Installing NextGIS Connect into QGIS 3?

                                                  One-line joke