Beautify for loop using stream and lambda












4















Currently I got this code:



@GetMapping("/all/")
public Iterable<Article> getAllArticle(){
ArrayList<ArticleEntity> articleEntities = Lists.newArrayList(articleProviderComponent.getAllArticle());
ArrayList<Article> articles = Lists.newArrayList();
for(ArticleEntity articleEntity : articleEntities){
articles.add(ArticleMapper.articleEntity2Article(articleEntity));
}
return articles;
}


The repository returns an Iterable, which I want to convert to a ArrayList. Beside that I want to convert each Entity to a POJO.



I tried using something like
list.foreach(ArticleMapper::ArticleMapper.articleEntity2Article) which works fine, but does not return a new list.










share|improve this question





























    4















    Currently I got this code:



    @GetMapping("/all/")
    public Iterable<Article> getAllArticle(){
    ArrayList<ArticleEntity> articleEntities = Lists.newArrayList(articleProviderComponent.getAllArticle());
    ArrayList<Article> articles = Lists.newArrayList();
    for(ArticleEntity articleEntity : articleEntities){
    articles.add(ArticleMapper.articleEntity2Article(articleEntity));
    }
    return articles;
    }


    The repository returns an Iterable, which I want to convert to a ArrayList. Beside that I want to convert each Entity to a POJO.



    I tried using something like
    list.foreach(ArticleMapper::ArticleMapper.articleEntity2Article) which works fine, but does not return a new list.










    share|improve this question



























      4












      4








      4








      Currently I got this code:



      @GetMapping("/all/")
      public Iterable<Article> getAllArticle(){
      ArrayList<ArticleEntity> articleEntities = Lists.newArrayList(articleProviderComponent.getAllArticle());
      ArrayList<Article> articles = Lists.newArrayList();
      for(ArticleEntity articleEntity : articleEntities){
      articles.add(ArticleMapper.articleEntity2Article(articleEntity));
      }
      return articles;
      }


      The repository returns an Iterable, which I want to convert to a ArrayList. Beside that I want to convert each Entity to a POJO.



      I tried using something like
      list.foreach(ArticleMapper::ArticleMapper.articleEntity2Article) which works fine, but does not return a new list.










      share|improve this question
















      Currently I got this code:



      @GetMapping("/all/")
      public Iterable<Article> getAllArticle(){
      ArrayList<ArticleEntity> articleEntities = Lists.newArrayList(articleProviderComponent.getAllArticle());
      ArrayList<Article> articles = Lists.newArrayList();
      for(ArticleEntity articleEntity : articleEntities){
      articles.add(ArticleMapper.articleEntity2Article(articleEntity));
      }
      return articles;
      }


      The repository returns an Iterable, which I want to convert to a ArrayList. Beside that I want to convert each Entity to a POJO.



      I tried using something like
      list.foreach(ArticleMapper::ArticleMapper.articleEntity2Article) which works fine, but does not return a new list.







      java java-stream






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 16 '18 at 11:51









      Stefan Zobel

      2,48231931




      2,48231931










      asked Nov 16 '18 at 7:25









      elpelp

      364116




      364116
























          4 Answers
          4






          active

          oldest

          votes


















          8














          A simple map will do the job:



          List<Article> articles = articleEntities.stream()
          .map(ArticleMapper::articleEntity2Article)
          .collect(Collectors.toList());


          map converts each element to something else using the method given.






          share|improve this answer

































            4














            Stream the List, map it to your target type and collect to a List:



            List<Article> articles = articleEntities.stream().map(ArticleMapper::articleEntity2Article).collect(Collectors.toList());





            share|improve this answer































              1














              Basically the other answers are showing the right direction. But if you want to keep the same semantics of your code something additional has to be taken into account.



              According to JavaDoc Collecotrs.toList




              Returns a Collector that accumulates the input elements into a new
              List. There are no guarantees on the type, mutability,
              serializability, or thread-safety of the List returned; if more
              control over the returned List is required, use
              toCollection(Supplier).




              The returned articles are of type ArrayList<ArticleEntity>. Thus this list is e.g. mutable.



              The return type of the method getAllArticle() is Iterable<Article>. Thus we can call



              Iterator<Article> iterator = getAllArticle().iterator(); 


              But if you need to call iterator.remove() "there are no guarantees on the [...] mutability" of the underlying collection. Hence this could result in an (JavaDoc)




              UnsupportedOperationException - if the remove operation is not
              supported by this iterator




              To keep the behaviour of the original code use Collectors.toCollection:



              List<Article> articles = articleEntities.stream()
              .map(ArticleMapper::articleEntity2Article)
              .collect(Collectors.toCollection(Lists::newArrayList));


              This will return articles built by Lists.newArrayList().






              share|improve this answer

































                0














                As Iterable is made to be as general as possible, it does not provide a capability to stream it's content, but with the help of StreamSupport you can generate a stream from the Iterable instance and reduce the amount of operations to one:



                final List<Article> articlesList = 
                StreamSupport.stream(articleProviderComponent.getAllArticle().spliterator(), false)
                .map(ArticleMapper::articleEntity2Article)
                .collect(Collectors.toList());





                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',
                  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%2f53333221%2fbeautify-for-loop-using-stream-and-lambda%23new-answer', 'question_page');
                  }
                  );

                  Post as a guest















                  Required, but never shown

























                  4 Answers
                  4






                  active

                  oldest

                  votes








                  4 Answers
                  4






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  8














                  A simple map will do the job:



                  List<Article> articles = articleEntities.stream()
                  .map(ArticleMapper::articleEntity2Article)
                  .collect(Collectors.toList());


                  map converts each element to something else using the method given.






                  share|improve this answer






























                    8














                    A simple map will do the job:



                    List<Article> articles = articleEntities.stream()
                    .map(ArticleMapper::articleEntity2Article)
                    .collect(Collectors.toList());


                    map converts each element to something else using the method given.






                    share|improve this answer




























                      8












                      8








                      8







                      A simple map will do the job:



                      List<Article> articles = articleEntities.stream()
                      .map(ArticleMapper::articleEntity2Article)
                      .collect(Collectors.toList());


                      map converts each element to something else using the method given.






                      share|improve this answer















                      A simple map will do the job:



                      List<Article> articles = articleEntities.stream()
                      .map(ArticleMapper::articleEntity2Article)
                      .collect(Collectors.toList());


                      map converts each element to something else using the method given.







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Nov 16 '18 at 20:02









                      Aomine

                      42.5k74676




                      42.5k74676










                      answered Nov 16 '18 at 7:28









                      SweeperSweeper

                      71.1k1075144




                      71.1k1075144

























                          4














                          Stream the List, map it to your target type and collect to a List:



                          List<Article> articles = articleEntities.stream().map(ArticleMapper::articleEntity2Article).collect(Collectors.toList());





                          share|improve this answer




























                            4














                            Stream the List, map it to your target type and collect to a List:



                            List<Article> articles = articleEntities.stream().map(ArticleMapper::articleEntity2Article).collect(Collectors.toList());





                            share|improve this answer


























                              4












                              4








                              4







                              Stream the List, map it to your target type and collect to a List:



                              List<Article> articles = articleEntities.stream().map(ArticleMapper::articleEntity2Article).collect(Collectors.toList());





                              share|improve this answer













                              Stream the List, map it to your target type and collect to a List:



                              List<Article> articles = articleEntities.stream().map(ArticleMapper::articleEntity2Article).collect(Collectors.toList());






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Nov 16 '18 at 7:28









                              EranEran

                              290k37477563




                              290k37477563























                                  1














                                  Basically the other answers are showing the right direction. But if you want to keep the same semantics of your code something additional has to be taken into account.



                                  According to JavaDoc Collecotrs.toList




                                  Returns a Collector that accumulates the input elements into a new
                                  List. There are no guarantees on the type, mutability,
                                  serializability, or thread-safety of the List returned; if more
                                  control over the returned List is required, use
                                  toCollection(Supplier).




                                  The returned articles are of type ArrayList<ArticleEntity>. Thus this list is e.g. mutable.



                                  The return type of the method getAllArticle() is Iterable<Article>. Thus we can call



                                  Iterator<Article> iterator = getAllArticle().iterator(); 


                                  But if you need to call iterator.remove() "there are no guarantees on the [...] mutability" of the underlying collection. Hence this could result in an (JavaDoc)




                                  UnsupportedOperationException - if the remove operation is not
                                  supported by this iterator




                                  To keep the behaviour of the original code use Collectors.toCollection:



                                  List<Article> articles = articleEntities.stream()
                                  .map(ArticleMapper::articleEntity2Article)
                                  .collect(Collectors.toCollection(Lists::newArrayList));


                                  This will return articles built by Lists.newArrayList().






                                  share|improve this answer






























                                    1














                                    Basically the other answers are showing the right direction. But if you want to keep the same semantics of your code something additional has to be taken into account.



                                    According to JavaDoc Collecotrs.toList




                                    Returns a Collector that accumulates the input elements into a new
                                    List. There are no guarantees on the type, mutability,
                                    serializability, or thread-safety of the List returned; if more
                                    control over the returned List is required, use
                                    toCollection(Supplier).




                                    The returned articles are of type ArrayList<ArticleEntity>. Thus this list is e.g. mutable.



                                    The return type of the method getAllArticle() is Iterable<Article>. Thus we can call



                                    Iterator<Article> iterator = getAllArticle().iterator(); 


                                    But if you need to call iterator.remove() "there are no guarantees on the [...] mutability" of the underlying collection. Hence this could result in an (JavaDoc)




                                    UnsupportedOperationException - if the remove operation is not
                                    supported by this iterator




                                    To keep the behaviour of the original code use Collectors.toCollection:



                                    List<Article> articles = articleEntities.stream()
                                    .map(ArticleMapper::articleEntity2Article)
                                    .collect(Collectors.toCollection(Lists::newArrayList));


                                    This will return articles built by Lists.newArrayList().






                                    share|improve this answer




























                                      1












                                      1








                                      1







                                      Basically the other answers are showing the right direction. But if you want to keep the same semantics of your code something additional has to be taken into account.



                                      According to JavaDoc Collecotrs.toList




                                      Returns a Collector that accumulates the input elements into a new
                                      List. There are no guarantees on the type, mutability,
                                      serializability, or thread-safety of the List returned; if more
                                      control over the returned List is required, use
                                      toCollection(Supplier).




                                      The returned articles are of type ArrayList<ArticleEntity>. Thus this list is e.g. mutable.



                                      The return type of the method getAllArticle() is Iterable<Article>. Thus we can call



                                      Iterator<Article> iterator = getAllArticle().iterator(); 


                                      But if you need to call iterator.remove() "there are no guarantees on the [...] mutability" of the underlying collection. Hence this could result in an (JavaDoc)




                                      UnsupportedOperationException - if the remove operation is not
                                      supported by this iterator




                                      To keep the behaviour of the original code use Collectors.toCollection:



                                      List<Article> articles = articleEntities.stream()
                                      .map(ArticleMapper::articleEntity2Article)
                                      .collect(Collectors.toCollection(Lists::newArrayList));


                                      This will return articles built by Lists.newArrayList().






                                      share|improve this answer















                                      Basically the other answers are showing the right direction. But if you want to keep the same semantics of your code something additional has to be taken into account.



                                      According to JavaDoc Collecotrs.toList




                                      Returns a Collector that accumulates the input elements into a new
                                      List. There are no guarantees on the type, mutability,
                                      serializability, or thread-safety of the List returned; if more
                                      control over the returned List is required, use
                                      toCollection(Supplier).




                                      The returned articles are of type ArrayList<ArticleEntity>. Thus this list is e.g. mutable.



                                      The return type of the method getAllArticle() is Iterable<Article>. Thus we can call



                                      Iterator<Article> iterator = getAllArticle().iterator(); 


                                      But if you need to call iterator.remove() "there are no guarantees on the [...] mutability" of the underlying collection. Hence this could result in an (JavaDoc)




                                      UnsupportedOperationException - if the remove operation is not
                                      supported by this iterator




                                      To keep the behaviour of the original code use Collectors.toCollection:



                                      List<Article> articles = articleEntities.stream()
                                      .map(ArticleMapper::articleEntity2Article)
                                      .collect(Collectors.toCollection(Lists::newArrayList));


                                      This will return articles built by Lists.newArrayList().







                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited Nov 16 '18 at 13:37

























                                      answered Nov 16 '18 at 8:25









                                      LuCioLuCio

                                      2,8921924




                                      2,8921924























                                          0














                                          As Iterable is made to be as general as possible, it does not provide a capability to stream it's content, but with the help of StreamSupport you can generate a stream from the Iterable instance and reduce the amount of operations to one:



                                          final List<Article> articlesList = 
                                          StreamSupport.stream(articleProviderComponent.getAllArticle().spliterator(), false)
                                          .map(ArticleMapper::articleEntity2Article)
                                          .collect(Collectors.toList());





                                          share|improve this answer






























                                            0














                                            As Iterable is made to be as general as possible, it does not provide a capability to stream it's content, but with the help of StreamSupport you can generate a stream from the Iterable instance and reduce the amount of operations to one:



                                            final List<Article> articlesList = 
                                            StreamSupport.stream(articleProviderComponent.getAllArticle().spliterator(), false)
                                            .map(ArticleMapper::articleEntity2Article)
                                            .collect(Collectors.toList());





                                            share|improve this answer




























                                              0












                                              0








                                              0







                                              As Iterable is made to be as general as possible, it does not provide a capability to stream it's content, but with the help of StreamSupport you can generate a stream from the Iterable instance and reduce the amount of operations to one:



                                              final List<Article> articlesList = 
                                              StreamSupport.stream(articleProviderComponent.getAllArticle().spliterator(), false)
                                              .map(ArticleMapper::articleEntity2Article)
                                              .collect(Collectors.toList());





                                              share|improve this answer















                                              As Iterable is made to be as general as possible, it does not provide a capability to stream it's content, but with the help of StreamSupport you can generate a stream from the Iterable instance and reduce the amount of operations to one:



                                              final List<Article> articlesList = 
                                              StreamSupport.stream(articleProviderComponent.getAllArticle().spliterator(), false)
                                              .map(ArticleMapper::articleEntity2Article)
                                              .collect(Collectors.toList());






                                              share|improve this answer














                                              share|improve this answer



                                              share|improve this answer








                                              edited Nov 16 '18 at 8:10

























                                              answered Nov 16 '18 at 8:04









                                              BradBrad

                                              1739




                                              1739






























                                                  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%2f53333221%2fbeautify-for-loop-using-stream-and-lambda%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

                                                  Xamarin.iOS Cant Deploy on Iphone

                                                  Glorious Revolution

                                                  Dulmage-Mendelsohn matrix decomposition in Python