adding an argument from the map method to the foreach method using Java Stream












2














I wrote a tiny example to explain my problem:



import java.util.Arrays;
import java.util.List;


public class Example {

public static void main( String args ) {
String array = {"1 0101 5","1 0101 5"};
Arrays.stream(array)
.map(str->str.split(" "))//every String is mapped to an array of String
.map(arr-> returnAListOf5Element( Integer.parseInt(arr[0]),arr[1],Integer.parseInt(arr[2])))
.forEach(list-> tesMyList(list));//i want to send the Integer.parseInt(arr[2]) as a second argument
}
/**
*
* test if the list has size of 5
*/
private static void testMyList(List<Integer> myList) {
if (myList.size()==5)
System.out.println("Ok");
}

/**
*
* return a list of 5 element
* @return
*/
private static List<Integer> returnAListOf5Element( int i, String s, int i1 ) {
List list = Arrays.asList(1,2,3,4,5);
return list;
}
}


So I have some Strings like "1 0101 5","1 0101 5"....., i use stream operation to make some calcul.



The problem is i want to add the argument arr[2] found in the map method to the testMyList method found in the foreach method.



the method testMyList should be like:



 private static void testMyList(List<Integer> myList, int size) {
if (myList.size()==size)
System.out.println("Ok");
}









share|improve this question
























  • Easiest thing is probably to collapse the .map.map.forEach into a single forEach that does all three things. (then you don't really need the stream anymore and can just use a for-in loop over the array.
    – Thilo
    Nov 21 '18 at 11:46










  • Another option is to have the second map step return both its real output and that extra integer you need for the next step (either as a pair of these two things or maybe as an array with now six elements).
    – Thilo
    Nov 21 '18 at 11:48






  • 1




    yes i see a discution about mapping to two element, but i found the solution more complicated than the normal for loop.
    – zak zak
    Nov 21 '18 at 11:49










  • Third option could "zip" together two streams, one with your arrays, and one with the integers. Must be careful that they exactly correspond to each-other in the sequence of these two streams.
    – Thilo
    Nov 21 '18 at 11:49










  • why returnAListOf5Element is accepting arguments but not doing anything with them ?
    – grsdev7
    Nov 21 '18 at 11:51
















2














I wrote a tiny example to explain my problem:



import java.util.Arrays;
import java.util.List;


public class Example {

public static void main( String args ) {
String array = {"1 0101 5","1 0101 5"};
Arrays.stream(array)
.map(str->str.split(" "))//every String is mapped to an array of String
.map(arr-> returnAListOf5Element( Integer.parseInt(arr[0]),arr[1],Integer.parseInt(arr[2])))
.forEach(list-> tesMyList(list));//i want to send the Integer.parseInt(arr[2]) as a second argument
}
/**
*
* test if the list has size of 5
*/
private static void testMyList(List<Integer> myList) {
if (myList.size()==5)
System.out.println("Ok");
}

/**
*
* return a list of 5 element
* @return
*/
private static List<Integer> returnAListOf5Element( int i, String s, int i1 ) {
List list = Arrays.asList(1,2,3,4,5);
return list;
}
}


So I have some Strings like "1 0101 5","1 0101 5"....., i use stream operation to make some calcul.



The problem is i want to add the argument arr[2] found in the map method to the testMyList method found in the foreach method.



the method testMyList should be like:



 private static void testMyList(List<Integer> myList, int size) {
if (myList.size()==size)
System.out.println("Ok");
}









share|improve this question
























  • Easiest thing is probably to collapse the .map.map.forEach into a single forEach that does all three things. (then you don't really need the stream anymore and can just use a for-in loop over the array.
    – Thilo
    Nov 21 '18 at 11:46










  • Another option is to have the second map step return both its real output and that extra integer you need for the next step (either as a pair of these two things or maybe as an array with now six elements).
    – Thilo
    Nov 21 '18 at 11:48






  • 1




    yes i see a discution about mapping to two element, but i found the solution more complicated than the normal for loop.
    – zak zak
    Nov 21 '18 at 11:49










  • Third option could "zip" together two streams, one with your arrays, and one with the integers. Must be careful that they exactly correspond to each-other in the sequence of these two streams.
    – Thilo
    Nov 21 '18 at 11:49










  • why returnAListOf5Element is accepting arguments but not doing anything with them ?
    – grsdev7
    Nov 21 '18 at 11:51














2












2








2


1





I wrote a tiny example to explain my problem:



import java.util.Arrays;
import java.util.List;


public class Example {

public static void main( String args ) {
String array = {"1 0101 5","1 0101 5"};
Arrays.stream(array)
.map(str->str.split(" "))//every String is mapped to an array of String
.map(arr-> returnAListOf5Element( Integer.parseInt(arr[0]),arr[1],Integer.parseInt(arr[2])))
.forEach(list-> tesMyList(list));//i want to send the Integer.parseInt(arr[2]) as a second argument
}
/**
*
* test if the list has size of 5
*/
private static void testMyList(List<Integer> myList) {
if (myList.size()==5)
System.out.println("Ok");
}

/**
*
* return a list of 5 element
* @return
*/
private static List<Integer> returnAListOf5Element( int i, String s, int i1 ) {
List list = Arrays.asList(1,2,3,4,5);
return list;
}
}


So I have some Strings like "1 0101 5","1 0101 5"....., i use stream operation to make some calcul.



The problem is i want to add the argument arr[2] found in the map method to the testMyList method found in the foreach method.



the method testMyList should be like:



 private static void testMyList(List<Integer> myList, int size) {
if (myList.size()==size)
System.out.println("Ok");
}









share|improve this question















I wrote a tiny example to explain my problem:



import java.util.Arrays;
import java.util.List;


public class Example {

public static void main( String args ) {
String array = {"1 0101 5","1 0101 5"};
Arrays.stream(array)
.map(str->str.split(" "))//every String is mapped to an array of String
.map(arr-> returnAListOf5Element( Integer.parseInt(arr[0]),arr[1],Integer.parseInt(arr[2])))
.forEach(list-> tesMyList(list));//i want to send the Integer.parseInt(arr[2]) as a second argument
}
/**
*
* test if the list has size of 5
*/
private static void testMyList(List<Integer> myList) {
if (myList.size()==5)
System.out.println("Ok");
}

/**
*
* return a list of 5 element
* @return
*/
private static List<Integer> returnAListOf5Element( int i, String s, int i1 ) {
List list = Arrays.asList(1,2,3,4,5);
return list;
}
}


So I have some Strings like "1 0101 5","1 0101 5"....., i use stream operation to make some calcul.



The problem is i want to add the argument arr[2] found in the map method to the testMyList method found in the foreach method.



the method testMyList should be like:



 private static void testMyList(List<Integer> myList, int size) {
if (myList.size()==size)
System.out.println("Ok");
}






java foreach java-8 java-stream






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 21 '18 at 12:13









Andrew Tobilko

26k104284




26k104284










asked Nov 21 '18 at 11:42









zak zak

494212




494212












  • Easiest thing is probably to collapse the .map.map.forEach into a single forEach that does all three things. (then you don't really need the stream anymore and can just use a for-in loop over the array.
    – Thilo
    Nov 21 '18 at 11:46










  • Another option is to have the second map step return both its real output and that extra integer you need for the next step (either as a pair of these two things or maybe as an array with now six elements).
    – Thilo
    Nov 21 '18 at 11:48






  • 1




    yes i see a discution about mapping to two element, but i found the solution more complicated than the normal for loop.
    – zak zak
    Nov 21 '18 at 11:49










  • Third option could "zip" together two streams, one with your arrays, and one with the integers. Must be careful that they exactly correspond to each-other in the sequence of these two streams.
    – Thilo
    Nov 21 '18 at 11:49










  • why returnAListOf5Element is accepting arguments but not doing anything with them ?
    – grsdev7
    Nov 21 '18 at 11:51


















  • Easiest thing is probably to collapse the .map.map.forEach into a single forEach that does all three things. (then you don't really need the stream anymore and can just use a for-in loop over the array.
    – Thilo
    Nov 21 '18 at 11:46










  • Another option is to have the second map step return both its real output and that extra integer you need for the next step (either as a pair of these two things or maybe as an array with now six elements).
    – Thilo
    Nov 21 '18 at 11:48






  • 1




    yes i see a discution about mapping to two element, but i found the solution more complicated than the normal for loop.
    – zak zak
    Nov 21 '18 at 11:49










  • Third option could "zip" together two streams, one with your arrays, and one with the integers. Must be careful that they exactly correspond to each-other in the sequence of these two streams.
    – Thilo
    Nov 21 '18 at 11:49










  • why returnAListOf5Element is accepting arguments but not doing anything with them ?
    – grsdev7
    Nov 21 '18 at 11:51
















Easiest thing is probably to collapse the .map.map.forEach into a single forEach that does all three things. (then you don't really need the stream anymore and can just use a for-in loop over the array.
– Thilo
Nov 21 '18 at 11:46




Easiest thing is probably to collapse the .map.map.forEach into a single forEach that does all three things. (then you don't really need the stream anymore and can just use a for-in loop over the array.
– Thilo
Nov 21 '18 at 11:46












Another option is to have the second map step return both its real output and that extra integer you need for the next step (either as a pair of these two things or maybe as an array with now six elements).
– Thilo
Nov 21 '18 at 11:48




Another option is to have the second map step return both its real output and that extra integer you need for the next step (either as a pair of these two things or maybe as an array with now six elements).
– Thilo
Nov 21 '18 at 11:48




1




1




yes i see a discution about mapping to two element, but i found the solution more complicated than the normal for loop.
– zak zak
Nov 21 '18 at 11:49




yes i see a discution about mapping to two element, but i found the solution more complicated than the normal for loop.
– zak zak
Nov 21 '18 at 11:49












Third option could "zip" together two streams, one with your arrays, and one with the integers. Must be careful that they exactly correspond to each-other in the sequence of these two streams.
– Thilo
Nov 21 '18 at 11:49




Third option could "zip" together two streams, one with your arrays, and one with the integers. Must be careful that they exactly correspond to each-other in the sequence of these two streams.
– Thilo
Nov 21 '18 at 11:49












why returnAListOf5Element is accepting arguments but not doing anything with them ?
– grsdev7
Nov 21 '18 at 11:51




why returnAListOf5Element is accepting arguments but not doing anything with them ?
– grsdev7
Nov 21 '18 at 11:51












2 Answers
2






active

oldest

votes


















4














I can see three possible solutions:




  1. returnAListOf5Element returns arr[2] within the list. (let's say, by contact, it's the last element in the returned list.) It's a dirty approach.


  2. map returns a Map.Entry<List<Integer>, Integer> which is composed of the result of the returnAListOf5Element(...) call and arr[2]. It's a more reasonable way.



These two ides are based on caching state of a previous operation so you can get it at a next one. It's the only way to obtain the result calculated in the chain before.




  1. You replace the stream chain with a simple loop where each intermediate calculation is accessible.


I find the last method the most simple and performance-wise. It doesn't seem that you are going to reap any benefits from streams here. I would stick to it.






share|improve this answer































    1














    Create your own class to maintain your data rather than using some generic one like List.



    class MyObject {
    public final int i;
    public final String string;
    public final int i1;
    public MyObject(int i, String string, int i1){
    this.i = i;
    this.string = string;
    this.i1 = i1;
    }
    public static MyObject parse(String line) {
    String split = line.split(" ");
    return new MyObject(Integer.parseInt(split[0], split[1], Integer.parseInt(split[2]);
    }
    }


    Then you can do



    Files.lines(filename)
    .map(MyObject::parse) // now you have a Stream of MyObjects
    .forEach(o -> verify(o));


    with eg



    void verify(MyObject object) {
    if (object.i1 < 5) {
    System.out.println("invalid");
    }
    }





    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%2f53411304%2fadding-an-argument-from-the-map-method-to-the-foreach-method-using-java-stream%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      4














      I can see three possible solutions:




      1. returnAListOf5Element returns arr[2] within the list. (let's say, by contact, it's the last element in the returned list.) It's a dirty approach.


      2. map returns a Map.Entry<List<Integer>, Integer> which is composed of the result of the returnAListOf5Element(...) call and arr[2]. It's a more reasonable way.



      These two ides are based on caching state of a previous operation so you can get it at a next one. It's the only way to obtain the result calculated in the chain before.




      1. You replace the stream chain with a simple loop where each intermediate calculation is accessible.


      I find the last method the most simple and performance-wise. It doesn't seem that you are going to reap any benefits from streams here. I would stick to it.






      share|improve this answer




























        4














        I can see three possible solutions:




        1. returnAListOf5Element returns arr[2] within the list. (let's say, by contact, it's the last element in the returned list.) It's a dirty approach.


        2. map returns a Map.Entry<List<Integer>, Integer> which is composed of the result of the returnAListOf5Element(...) call and arr[2]. It's a more reasonable way.



        These two ides are based on caching state of a previous operation so you can get it at a next one. It's the only way to obtain the result calculated in the chain before.




        1. You replace the stream chain with a simple loop where each intermediate calculation is accessible.


        I find the last method the most simple and performance-wise. It doesn't seem that you are going to reap any benefits from streams here. I would stick to it.






        share|improve this answer


























          4












          4








          4






          I can see three possible solutions:




          1. returnAListOf5Element returns arr[2] within the list. (let's say, by contact, it's the last element in the returned list.) It's a dirty approach.


          2. map returns a Map.Entry<List<Integer>, Integer> which is composed of the result of the returnAListOf5Element(...) call and arr[2]. It's a more reasonable way.



          These two ides are based on caching state of a previous operation so you can get it at a next one. It's the only way to obtain the result calculated in the chain before.




          1. You replace the stream chain with a simple loop where each intermediate calculation is accessible.


          I find the last method the most simple and performance-wise. It doesn't seem that you are going to reap any benefits from streams here. I would stick to it.






          share|improve this answer














          I can see three possible solutions:




          1. returnAListOf5Element returns arr[2] within the list. (let's say, by contact, it's the last element in the returned list.) It's a dirty approach.


          2. map returns a Map.Entry<List<Integer>, Integer> which is composed of the result of the returnAListOf5Element(...) call and arr[2]. It's a more reasonable way.



          These two ides are based on caching state of a previous operation so you can get it at a next one. It's the only way to obtain the result calculated in the chain before.




          1. You replace the stream chain with a simple loop where each intermediate calculation is accessible.


          I find the last method the most simple and performance-wise. It doesn't seem that you are going to reap any benefits from streams here. I would stick to it.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 21 '18 at 14:52

























          answered Nov 21 '18 at 11:50









          Andrew Tobilko

          26k104284




          26k104284

























              1














              Create your own class to maintain your data rather than using some generic one like List.



              class MyObject {
              public final int i;
              public final String string;
              public final int i1;
              public MyObject(int i, String string, int i1){
              this.i = i;
              this.string = string;
              this.i1 = i1;
              }
              public static MyObject parse(String line) {
              String split = line.split(" ");
              return new MyObject(Integer.parseInt(split[0], split[1], Integer.parseInt(split[2]);
              }
              }


              Then you can do



              Files.lines(filename)
              .map(MyObject::parse) // now you have a Stream of MyObjects
              .forEach(o -> verify(o));


              with eg



              void verify(MyObject object) {
              if (object.i1 < 5) {
              System.out.println("invalid");
              }
              }





              share|improve this answer


























                1














                Create your own class to maintain your data rather than using some generic one like List.



                class MyObject {
                public final int i;
                public final String string;
                public final int i1;
                public MyObject(int i, String string, int i1){
                this.i = i;
                this.string = string;
                this.i1 = i1;
                }
                public static MyObject parse(String line) {
                String split = line.split(" ");
                return new MyObject(Integer.parseInt(split[0], split[1], Integer.parseInt(split[2]);
                }
                }


                Then you can do



                Files.lines(filename)
                .map(MyObject::parse) // now you have a Stream of MyObjects
                .forEach(o -> verify(o));


                with eg



                void verify(MyObject object) {
                if (object.i1 < 5) {
                System.out.println("invalid");
                }
                }





                share|improve this answer
























                  1












                  1








                  1






                  Create your own class to maintain your data rather than using some generic one like List.



                  class MyObject {
                  public final int i;
                  public final String string;
                  public final int i1;
                  public MyObject(int i, String string, int i1){
                  this.i = i;
                  this.string = string;
                  this.i1 = i1;
                  }
                  public static MyObject parse(String line) {
                  String split = line.split(" ");
                  return new MyObject(Integer.parseInt(split[0], split[1], Integer.parseInt(split[2]);
                  }
                  }


                  Then you can do



                  Files.lines(filename)
                  .map(MyObject::parse) // now you have a Stream of MyObjects
                  .forEach(o -> verify(o));


                  with eg



                  void verify(MyObject object) {
                  if (object.i1 < 5) {
                  System.out.println("invalid");
                  }
                  }





                  share|improve this answer












                  Create your own class to maintain your data rather than using some generic one like List.



                  class MyObject {
                  public final int i;
                  public final String string;
                  public final int i1;
                  public MyObject(int i, String string, int i1){
                  this.i = i;
                  this.string = string;
                  this.i1 = i1;
                  }
                  public static MyObject parse(String line) {
                  String split = line.split(" ");
                  return new MyObject(Integer.parseInt(split[0], split[1], Integer.parseInt(split[2]);
                  }
                  }


                  Then you can do



                  Files.lines(filename)
                  .map(MyObject::parse) // now you have a Stream of MyObjects
                  .forEach(o -> verify(o));


                  with eg



                  void verify(MyObject object) {
                  if (object.i1 < 5) {
                  System.out.println("invalid");
                  }
                  }






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 21 '18 at 11:52









                  daniu

                  7,23521635




                  7,23521635






























                      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.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • 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%2f53411304%2fadding-an-argument-from-the-map-method-to-the-foreach-method-using-java-stream%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

                      404 Error Contact Form 7 ajax form submitting

                      How to know if a Active Directory user can login interactively

                      TypeError: fit_transform() missing 1 required positional argument: 'X'