Lambda expressions in Java using predicate object in filter2019 Community Moderator ElectionIs Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?What is the difference between public, protected, package-private and private in Java?How do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?list comprehension vs. lambda + filterHow do I convert a String to an int in Java?Creating a memory leak with JavaWhat is a lambda expression in C++11?

Hotkey (or other quick way) to insert a keyframe for only one component of a vector-valued property?

Are all players supposed to be able to see each others' character sheets?

Conservation of Mass and Energy

Accepted offer letter, position changed

Can one live in the U.S. and not use a credit card?

How do I express some one as a black person?

When a wind turbine does not produce enough electricity how does the power company compensate for the loss?

Accountant/ lawyer will not return my call

When traveling to Europe from North America, do I need to purchase a different power strip?

Why was Goose renamed from Chewie for the Captain Marvel film?

Why does Captain Marvel assume the people on this planet know this?

An alternative proof of an application of Hahn-Banach

Difference on montgomery curve equation between EFD and RFC7748

Virginia employer terminated employee and wants signing bonus returned

Am I not good enough for you?

What's the "normal" opposite of flautando?

Should I take out a loan for a friend to invest on my behalf?

Shifting between bemols (flats) and diesis (sharps)in the key signature

Can you reject a postdoc offer after the PI has paid a large sum for flights/accommodation for your visit?

How to write ı (i without dot) character in pgf-pie

Are babies of evil humanoid species inherently evil?

What Happens when Passenger Refuses to Fly Boeing 737 Max?

Is it necessary to separate DC power cables and data cables?

Counting all the hearts



Lambda expressions in Java using predicate object in filter



2019 Community Moderator ElectionIs Java “pass-by-reference” or “pass-by-value”?How do I efficiently iterate over each entry in a Java Map?What is the difference between public, protected, package-private and private in Java?How do I read / convert an InputStream into a String in Java?When to use LinkedList over ArrayList in Java?How do I generate random integers within a specific range in Java?list comprehension vs. lambda + filterHow do I convert a String to an int in Java?Creating a memory leak with JavaWhat is a lambda expression in C++11?










0















This is simple code selecting a random subset of integers from a list of integers using lambda expressions. What the function is doing is, iterate through the list and for each element a random boolean value is called. Based on that element is selected or discarded.



public static List<Integer> getRandomSubsetUsingLambda(List<Integer> list) 
List<Integer> randomSubset = new ArrayList<>();
Random random = new Random();
Predicate<Object> flipCoin = o ->
return random.nextBoolean();
;

randomSubset = list.stream().filter(flipCoin).collect(Collectors.toList());
return randomSubset;



My understanding is that filter, based on ta boolean value selects the integers. But I didn't understand how is that happening. Does it mean that whenever flipCoin is called a boolean value is returned?










share|improve this question







New contributor




Avinash MV is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 2





    Add System.out.println("flipCoing called for " + o); just before return random.nextBoolean(); in your lambda expression, then run your stream again. You'll see.

    – ernest_k
    Mar 7 at 6:31















0















This is simple code selecting a random subset of integers from a list of integers using lambda expressions. What the function is doing is, iterate through the list and for each element a random boolean value is called. Based on that element is selected or discarded.



public static List<Integer> getRandomSubsetUsingLambda(List<Integer> list) 
List<Integer> randomSubset = new ArrayList<>();
Random random = new Random();
Predicate<Object> flipCoin = o ->
return random.nextBoolean();
;

randomSubset = list.stream().filter(flipCoin).collect(Collectors.toList());
return randomSubset;



My understanding is that filter, based on ta boolean value selects the integers. But I didn't understand how is that happening. Does it mean that whenever flipCoin is called a boolean value is returned?










share|improve this question







New contributor




Avinash MV is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 2





    Add System.out.println("flipCoing called for " + o); just before return random.nextBoolean(); in your lambda expression, then run your stream again. You'll see.

    – ernest_k
    Mar 7 at 6:31













0












0








0








This is simple code selecting a random subset of integers from a list of integers using lambda expressions. What the function is doing is, iterate through the list and for each element a random boolean value is called. Based on that element is selected or discarded.



public static List<Integer> getRandomSubsetUsingLambda(List<Integer> list) 
List<Integer> randomSubset = new ArrayList<>();
Random random = new Random();
Predicate<Object> flipCoin = o ->
return random.nextBoolean();
;

randomSubset = list.stream().filter(flipCoin).collect(Collectors.toList());
return randomSubset;



My understanding is that filter, based on ta boolean value selects the integers. But I didn't understand how is that happening. Does it mean that whenever flipCoin is called a boolean value is returned?










share|improve this question







New contributor




Avinash MV is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












This is simple code selecting a random subset of integers from a list of integers using lambda expressions. What the function is doing is, iterate through the list and for each element a random boolean value is called. Based on that element is selected or discarded.



public static List<Integer> getRandomSubsetUsingLambda(List<Integer> list) 
List<Integer> randomSubset = new ArrayList<>();
Random random = new Random();
Predicate<Object> flipCoin = o ->
return random.nextBoolean();
;

randomSubset = list.stream().filter(flipCoin).collect(Collectors.toList());
return randomSubset;



My understanding is that filter, based on ta boolean value selects the integers. But I didn't understand how is that happening. Does it mean that whenever flipCoin is called a boolean value is returned?







java lambda






share|improve this question







New contributor




Avinash MV is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question







New contributor




Avinash MV is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question






New contributor




Avinash MV is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked Mar 7 at 6:26









Avinash MVAvinash MV

12




12




New contributor




Avinash MV is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Avinash MV is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Avinash MV is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







  • 2





    Add System.out.println("flipCoing called for " + o); just before return random.nextBoolean(); in your lambda expression, then run your stream again. You'll see.

    – ernest_k
    Mar 7 at 6:31












  • 2





    Add System.out.println("flipCoing called for " + o); just before return random.nextBoolean(); in your lambda expression, then run your stream again. You'll see.

    – ernest_k
    Mar 7 at 6:31







2




2





Add System.out.println("flipCoing called for " + o); just before return random.nextBoolean(); in your lambda expression, then run your stream again. You'll see.

– ernest_k
Mar 7 at 6:31





Add System.out.println("flipCoing called for " + o); just before return random.nextBoolean(); in your lambda expression, then run your stream again. You'll see.

– ernest_k
Mar 7 at 6:31












3 Answers
3






active

oldest

votes


















0














filter() will call to flipCoin passing as parameter the iterated value from the stream.
Then flipCoin will generate a random boolean (ignoring the value of its parameter) and if false the iterated value from the stream will be discarded.



i.e. for each element in the stream a random boolean is generated and used to decide (randomly) if the element is accepted or discarded.






share|improve this answer






























    0














    By passing a lambda to filter, you're making it invoke apply method every time an object passes by. I this example every time random.nextBoolean(); is invoked, so it's a coin flip;)






    share|improve this answer






























      0














      Let's pick a practical example with a List containing three elements [1, 2, 3]



      1



      list.stream()
      .filter(flipCoin) // random.nextBoolean() returns true so 1 goes through
      .collect(Collectors.toList()); // 1 is waiting to be added to the list


      2



      list.stream()
      .filter(flipCoin) // random.nextBoolean() returns false and 2 is blocked
      .collect(Collectors.toList());


      3



      list.stream()
      .filter(flipCoin) // random.nextBoolean() returns true
      .collect(Collectors.toList()); // 3 is the last element of your stream so the list is created


      The new List contains [1, 3]



      Basically, everytime filter(flipCoin) is invoked, the following block code is executed for each element going through it (here Integers)



      public boolean test(Object o) 
      return random.nextBoolean();




      Basically, your stream is the equivalent of the following code block



      List<Integer> newList = new ArrayList<>();
      for (Integer i : list)
      boolean shouldBeAddedToNewList = random.nextBoolean();
      if (shouldBeAddedToNewList)
      newList.add(i);







      share|improve this answer























      • Got it. Thanks. One small doubt, I think the in the flipCoin lambda expression, 'o' is of type integer. So I could write Predicate<Integer> to be more precise. Please correct me if am wrong.

        – Avinash MV
        Mar 8 at 17:14










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



      );






      Avinash MV is a new contributor. Be nice, and check out our Code of Conduct.









      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55037337%2flambda-expressions-in-java-using-predicate-object-in-filter%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









      0














      filter() will call to flipCoin passing as parameter the iterated value from the stream.
      Then flipCoin will generate a random boolean (ignoring the value of its parameter) and if false the iterated value from the stream will be discarded.



      i.e. for each element in the stream a random boolean is generated and used to decide (randomly) if the element is accepted or discarded.






      share|improve this answer



























        0














        filter() will call to flipCoin passing as parameter the iterated value from the stream.
        Then flipCoin will generate a random boolean (ignoring the value of its parameter) and if false the iterated value from the stream will be discarded.



        i.e. for each element in the stream a random boolean is generated and used to decide (randomly) if the element is accepted or discarded.






        share|improve this answer

























          0












          0








          0







          filter() will call to flipCoin passing as parameter the iterated value from the stream.
          Then flipCoin will generate a random boolean (ignoring the value of its parameter) and if false the iterated value from the stream will be discarded.



          i.e. for each element in the stream a random boolean is generated and used to decide (randomly) if the element is accepted or discarded.






          share|improve this answer













          filter() will call to flipCoin passing as parameter the iterated value from the stream.
          Then flipCoin will generate a random boolean (ignoring the value of its parameter) and if false the iterated value from the stream will be discarded.



          i.e. for each element in the stream a random boolean is generated and used to decide (randomly) if the element is accepted or discarded.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 7 at 6:29









          Paco AbatoPaco Abato

          2,97731836




          2,97731836























              0














              By passing a lambda to filter, you're making it invoke apply method every time an object passes by. I this example every time random.nextBoolean(); is invoked, so it's a coin flip;)






              share|improve this answer



























                0














                By passing a lambda to filter, you're making it invoke apply method every time an object passes by. I this example every time random.nextBoolean(); is invoked, so it's a coin flip;)






                share|improve this answer

























                  0












                  0








                  0







                  By passing a lambda to filter, you're making it invoke apply method every time an object passes by. I this example every time random.nextBoolean(); is invoked, so it's a coin flip;)






                  share|improve this answer













                  By passing a lambda to filter, you're making it invoke apply method every time an object passes by. I this example every time random.nextBoolean(); is invoked, so it's a coin flip;)







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 7 at 6:30









                  AndronicusAndronicus

                  4,36121430




                  4,36121430





















                      0














                      Let's pick a practical example with a List containing three elements [1, 2, 3]



                      1



                      list.stream()
                      .filter(flipCoin) // random.nextBoolean() returns true so 1 goes through
                      .collect(Collectors.toList()); // 1 is waiting to be added to the list


                      2



                      list.stream()
                      .filter(flipCoin) // random.nextBoolean() returns false and 2 is blocked
                      .collect(Collectors.toList());


                      3



                      list.stream()
                      .filter(flipCoin) // random.nextBoolean() returns true
                      .collect(Collectors.toList()); // 3 is the last element of your stream so the list is created


                      The new List contains [1, 3]



                      Basically, everytime filter(flipCoin) is invoked, the following block code is executed for each element going through it (here Integers)



                      public boolean test(Object o) 
                      return random.nextBoolean();




                      Basically, your stream is the equivalent of the following code block



                      List<Integer> newList = new ArrayList<>();
                      for (Integer i : list)
                      boolean shouldBeAddedToNewList = random.nextBoolean();
                      if (shouldBeAddedToNewList)
                      newList.add(i);







                      share|improve this answer























                      • Got it. Thanks. One small doubt, I think the in the flipCoin lambda expression, 'o' is of type integer. So I could write Predicate<Integer> to be more precise. Please correct me if am wrong.

                        – Avinash MV
                        Mar 8 at 17:14















                      0














                      Let's pick a practical example with a List containing three elements [1, 2, 3]



                      1



                      list.stream()
                      .filter(flipCoin) // random.nextBoolean() returns true so 1 goes through
                      .collect(Collectors.toList()); // 1 is waiting to be added to the list


                      2



                      list.stream()
                      .filter(flipCoin) // random.nextBoolean() returns false and 2 is blocked
                      .collect(Collectors.toList());


                      3



                      list.stream()
                      .filter(flipCoin) // random.nextBoolean() returns true
                      .collect(Collectors.toList()); // 3 is the last element of your stream so the list is created


                      The new List contains [1, 3]



                      Basically, everytime filter(flipCoin) is invoked, the following block code is executed for each element going through it (here Integers)



                      public boolean test(Object o) 
                      return random.nextBoolean();




                      Basically, your stream is the equivalent of the following code block



                      List<Integer> newList = new ArrayList<>();
                      for (Integer i : list)
                      boolean shouldBeAddedToNewList = random.nextBoolean();
                      if (shouldBeAddedToNewList)
                      newList.add(i);







                      share|improve this answer























                      • Got it. Thanks. One small doubt, I think the in the flipCoin lambda expression, 'o' is of type integer. So I could write Predicate<Integer> to be more precise. Please correct me if am wrong.

                        – Avinash MV
                        Mar 8 at 17:14













                      0












                      0








                      0







                      Let's pick a practical example with a List containing three elements [1, 2, 3]



                      1



                      list.stream()
                      .filter(flipCoin) // random.nextBoolean() returns true so 1 goes through
                      .collect(Collectors.toList()); // 1 is waiting to be added to the list


                      2



                      list.stream()
                      .filter(flipCoin) // random.nextBoolean() returns false and 2 is blocked
                      .collect(Collectors.toList());


                      3



                      list.stream()
                      .filter(flipCoin) // random.nextBoolean() returns true
                      .collect(Collectors.toList()); // 3 is the last element of your stream so the list is created


                      The new List contains [1, 3]



                      Basically, everytime filter(flipCoin) is invoked, the following block code is executed for each element going through it (here Integers)



                      public boolean test(Object o) 
                      return random.nextBoolean();




                      Basically, your stream is the equivalent of the following code block



                      List<Integer> newList = new ArrayList<>();
                      for (Integer i : list)
                      boolean shouldBeAddedToNewList = random.nextBoolean();
                      if (shouldBeAddedToNewList)
                      newList.add(i);







                      share|improve this answer













                      Let's pick a practical example with a List containing three elements [1, 2, 3]



                      1



                      list.stream()
                      .filter(flipCoin) // random.nextBoolean() returns true so 1 goes through
                      .collect(Collectors.toList()); // 1 is waiting to be added to the list


                      2



                      list.stream()
                      .filter(flipCoin) // random.nextBoolean() returns false and 2 is blocked
                      .collect(Collectors.toList());


                      3



                      list.stream()
                      .filter(flipCoin) // random.nextBoolean() returns true
                      .collect(Collectors.toList()); // 3 is the last element of your stream so the list is created


                      The new List contains [1, 3]



                      Basically, everytime filter(flipCoin) is invoked, the following block code is executed for each element going through it (here Integers)



                      public boolean test(Object o) 
                      return random.nextBoolean();




                      Basically, your stream is the equivalent of the following code block



                      List<Integer> newList = new ArrayList<>();
                      for (Integer i : list)
                      boolean shouldBeAddedToNewList = random.nextBoolean();
                      if (shouldBeAddedToNewList)
                      newList.add(i);








                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Mar 7 at 6:33









                      Yassin HajajYassin Hajaj

                      13.9k72860




                      13.9k72860












                      • Got it. Thanks. One small doubt, I think the in the flipCoin lambda expression, 'o' is of type integer. So I could write Predicate<Integer> to be more precise. Please correct me if am wrong.

                        – Avinash MV
                        Mar 8 at 17:14

















                      • Got it. Thanks. One small doubt, I think the in the flipCoin lambda expression, 'o' is of type integer. So I could write Predicate<Integer> to be more precise. Please correct me if am wrong.

                        – Avinash MV
                        Mar 8 at 17:14
















                      Got it. Thanks. One small doubt, I think the in the flipCoin lambda expression, 'o' is of type integer. So I could write Predicate<Integer> to be more precise. Please correct me if am wrong.

                      – Avinash MV
                      Mar 8 at 17:14





                      Got it. Thanks. One small doubt, I think the in the flipCoin lambda expression, 'o' is of type integer. So I could write Predicate<Integer> to be more precise. Please correct me if am wrong.

                      – Avinash MV
                      Mar 8 at 17:14










                      Avinash MV is a new contributor. Be nice, and check out our Code of Conduct.









                      draft saved

                      draft discarded


















                      Avinash MV is a new contributor. Be nice, and check out our Code of Conduct.












                      Avinash MV is a new contributor. Be nice, and check out our Code of Conduct.











                      Avinash MV is a new contributor. Be nice, and check out our Code of Conduct.














                      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%2f55037337%2flambda-expressions-in-java-using-predicate-object-in-filter%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

                      Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

                      2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

                      Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme