Math.toIntExact inside lambda expression?












3















I'm learning about lambda expressions.
Given a list of names, I want to count the numbers of names that start with N.



I did that:



final static List<String> friends = Arrays.asList("Brian", "Nate", "Neal", "Raju", "Sara", "Scott");

public static int countFriendsStartWithN() {
return Math.toIntExact(friends
.stream()
.filter(name -> name.startsWith("N"))
.count());
}


The call to the count method returns a primitive long but I want an int.

I used Math.toIntExact to get the long value as int.



Is it possible to get the int value directly inside the lambda expression?










share|improve this question

























  • What do you mean by lambda experssion? That looks alright to me.

    – SamzSakerz
    Nov 16 '18 at 8:10






  • 3





    If you know the long value is not too large, you can simply cast it to int.

    – Eran
    Nov 16 '18 at 8:11






  • 2





    @Eran and you know it's not too large, because it is necessarily no greater than the number of items in a collection, which is an int.

    – Andy Turner
    Nov 16 '18 at 8:14











  • I just want to know if is possible to do the int conversion inside the stream process.

    – Jesus Zavarce
    Nov 16 '18 at 8:16
















3















I'm learning about lambda expressions.
Given a list of names, I want to count the numbers of names that start with N.



I did that:



final static List<String> friends = Arrays.asList("Brian", "Nate", "Neal", "Raju", "Sara", "Scott");

public static int countFriendsStartWithN() {
return Math.toIntExact(friends
.stream()
.filter(name -> name.startsWith("N"))
.count());
}


The call to the count method returns a primitive long but I want an int.

I used Math.toIntExact to get the long value as int.



Is it possible to get the int value directly inside the lambda expression?










share|improve this question

























  • What do you mean by lambda experssion? That looks alright to me.

    – SamzSakerz
    Nov 16 '18 at 8:10






  • 3





    If you know the long value is not too large, you can simply cast it to int.

    – Eran
    Nov 16 '18 at 8:11






  • 2





    @Eran and you know it's not too large, because it is necessarily no greater than the number of items in a collection, which is an int.

    – Andy Turner
    Nov 16 '18 at 8:14











  • I just want to know if is possible to do the int conversion inside the stream process.

    – Jesus Zavarce
    Nov 16 '18 at 8:16














3












3








3








I'm learning about lambda expressions.
Given a list of names, I want to count the numbers of names that start with N.



I did that:



final static List<String> friends = Arrays.asList("Brian", "Nate", "Neal", "Raju", "Sara", "Scott");

public static int countFriendsStartWithN() {
return Math.toIntExact(friends
.stream()
.filter(name -> name.startsWith("N"))
.count());
}


The call to the count method returns a primitive long but I want an int.

I used Math.toIntExact to get the long value as int.



Is it possible to get the int value directly inside the lambda expression?










share|improve this question
















I'm learning about lambda expressions.
Given a list of names, I want to count the numbers of names that start with N.



I did that:



final static List<String> friends = Arrays.asList("Brian", "Nate", "Neal", "Raju", "Sara", "Scott");

public static int countFriendsStartWithN() {
return Math.toIntExact(friends
.stream()
.filter(name -> name.startsWith("N"))
.count());
}


The call to the count method returns a primitive long but I want an int.

I used Math.toIntExact to get the long value as int.



Is it possible to get the int value directly inside the lambda expression?







java lambda






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 16 '18 at 8:38







Jesus Zavarce

















asked Nov 16 '18 at 8:09









Jesus ZavarceJesus Zavarce

1,069819




1,069819













  • What do you mean by lambda experssion? That looks alright to me.

    – SamzSakerz
    Nov 16 '18 at 8:10






  • 3





    If you know the long value is not too large, you can simply cast it to int.

    – Eran
    Nov 16 '18 at 8:11






  • 2





    @Eran and you know it's not too large, because it is necessarily no greater than the number of items in a collection, which is an int.

    – Andy Turner
    Nov 16 '18 at 8:14











  • I just want to know if is possible to do the int conversion inside the stream process.

    – Jesus Zavarce
    Nov 16 '18 at 8:16



















  • What do you mean by lambda experssion? That looks alright to me.

    – SamzSakerz
    Nov 16 '18 at 8:10






  • 3





    If you know the long value is not too large, you can simply cast it to int.

    – Eran
    Nov 16 '18 at 8:11






  • 2





    @Eran and you know it's not too large, because it is necessarily no greater than the number of items in a collection, which is an int.

    – Andy Turner
    Nov 16 '18 at 8:14











  • I just want to know if is possible to do the int conversion inside the stream process.

    – Jesus Zavarce
    Nov 16 '18 at 8:16

















What do you mean by lambda experssion? That looks alright to me.

– SamzSakerz
Nov 16 '18 at 8:10





What do you mean by lambda experssion? That looks alright to me.

– SamzSakerz
Nov 16 '18 at 8:10




3




3





If you know the long value is not too large, you can simply cast it to int.

– Eran
Nov 16 '18 at 8:11





If you know the long value is not too large, you can simply cast it to int.

– Eran
Nov 16 '18 at 8:11




2




2





@Eran and you know it's not too large, because it is necessarily no greater than the number of items in a collection, which is an int.

– Andy Turner
Nov 16 '18 at 8:14





@Eran and you know it's not too large, because it is necessarily no greater than the number of items in a collection, which is an int.

– Andy Turner
Nov 16 '18 at 8:14













I just want to know if is possible to do the int conversion inside the stream process.

– Jesus Zavarce
Nov 16 '18 at 8:16





I just want to know if is possible to do the int conversion inside the stream process.

– Jesus Zavarce
Nov 16 '18 at 8:16












5 Answers
5






active

oldest

votes


















6














No, it is not possible to fit your call to toIntExact into your chain of method calls, your stream pipeline. This is because count is a terminal operation and returns a primitive long on which no method call is possible. A terminal operation is an operation that ends the stream pipeline and produces a result (or a side effect).



So I believe the best thing you can do is to live with the code you already have. IMHO it’s fine.






share|improve this answer































    5














    Well, here's a somewhat silly way of calculating the count as an int without casting:



    public static int countFriendsStartWithN() {
    return friends.stream()
    .filter(name -> name.startsWith("N"))
    .mapToInt (s -> 1)
    .sum();
    }





    share|improve this answer































      4














      You can't do anything inside the lambda expression you currently have, since that's a Predicate: it returns a boolean. Math.toIntExact returns an int.



      You can do it without the Math.toIntExact (or a simple cast) like so:



      return /* create stream, filter */
      .mapToInt(a -> 1).sum();


      But this is likely to be slower than doing what you are doing at the moment.






      share|improve this answer































        3














        Yet another option that is not really better - it is possible to use a collector that applies a finisher:



        public static int countFriendsStartWithN() {
        return friends.stream()
        .filter(name -> name.startsWith("N"))
        .collect(Collectors.collectingAndThen(Collectors.counting(), Math::toIntExact));
        }


        This may have an advantage if you need it frequenty - you could build a utility method returning this Collector to make it reusable.






        share|improve this answer

































          2














          Here's a way to do this with reduce



          public static int countFriendsStartWithN2() {
          return friends
          .stream()
          .filter(name -> name.startsWith("N"))
          .map(s -> 1)
          .reduce(0, Integer::sum);
          }





          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%2f53333790%2fmath-tointexact-inside-lambda-expression%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            5 Answers
            5






            active

            oldest

            votes








            5 Answers
            5






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            6














            No, it is not possible to fit your call to toIntExact into your chain of method calls, your stream pipeline. This is because count is a terminal operation and returns a primitive long on which no method call is possible. A terminal operation is an operation that ends the stream pipeline and produces a result (or a side effect).



            So I believe the best thing you can do is to live with the code you already have. IMHO it’s fine.






            share|improve this answer




























              6














              No, it is not possible to fit your call to toIntExact into your chain of method calls, your stream pipeline. This is because count is a terminal operation and returns a primitive long on which no method call is possible. A terminal operation is an operation that ends the stream pipeline and produces a result (or a side effect).



              So I believe the best thing you can do is to live with the code you already have. IMHO it’s fine.






              share|improve this answer


























                6












                6








                6







                No, it is not possible to fit your call to toIntExact into your chain of method calls, your stream pipeline. This is because count is a terminal operation and returns a primitive long on which no method call is possible. A terminal operation is an operation that ends the stream pipeline and produces a result (or a side effect).



                So I believe the best thing you can do is to live with the code you already have. IMHO it’s fine.






                share|improve this answer













                No, it is not possible to fit your call to toIntExact into your chain of method calls, your stream pipeline. This is because count is a terminal operation and returns a primitive long on which no method call is possible. A terminal operation is an operation that ends the stream pipeline and produces a result (or a side effect).



                So I believe the best thing you can do is to live with the code you already have. IMHO it’s fine.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 16 '18 at 8:14









                Ole V.V.Ole V.V.

                31.8k74257




                31.8k74257

























                    5














                    Well, here's a somewhat silly way of calculating the count as an int without casting:



                    public static int countFriendsStartWithN() {
                    return friends.stream()
                    .filter(name -> name.startsWith("N"))
                    .mapToInt (s -> 1)
                    .sum();
                    }





                    share|improve this answer




























                      5














                      Well, here's a somewhat silly way of calculating the count as an int without casting:



                      public static int countFriendsStartWithN() {
                      return friends.stream()
                      .filter(name -> name.startsWith("N"))
                      .mapToInt (s -> 1)
                      .sum();
                      }





                      share|improve this answer


























                        5












                        5








                        5







                        Well, here's a somewhat silly way of calculating the count as an int without casting:



                        public static int countFriendsStartWithN() {
                        return friends.stream()
                        .filter(name -> name.startsWith("N"))
                        .mapToInt (s -> 1)
                        .sum();
                        }





                        share|improve this answer













                        Well, here's a somewhat silly way of calculating the count as an int without casting:



                        public static int countFriendsStartWithN() {
                        return friends.stream()
                        .filter(name -> name.startsWith("N"))
                        .mapToInt (s -> 1)
                        .sum();
                        }






                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Nov 16 '18 at 8:18









                        EranEran

                        290k37478563




                        290k37478563























                            4














                            You can't do anything inside the lambda expression you currently have, since that's a Predicate: it returns a boolean. Math.toIntExact returns an int.



                            You can do it without the Math.toIntExact (or a simple cast) like so:



                            return /* create stream, filter */
                            .mapToInt(a -> 1).sum();


                            But this is likely to be slower than doing what you are doing at the moment.






                            share|improve this answer




























                              4














                              You can't do anything inside the lambda expression you currently have, since that's a Predicate: it returns a boolean. Math.toIntExact returns an int.



                              You can do it without the Math.toIntExact (or a simple cast) like so:



                              return /* create stream, filter */
                              .mapToInt(a -> 1).sum();


                              But this is likely to be slower than doing what you are doing at the moment.






                              share|improve this answer


























                                4












                                4








                                4







                                You can't do anything inside the lambda expression you currently have, since that's a Predicate: it returns a boolean. Math.toIntExact returns an int.



                                You can do it without the Math.toIntExact (or a simple cast) like so:



                                return /* create stream, filter */
                                .mapToInt(a -> 1).sum();


                                But this is likely to be slower than doing what you are doing at the moment.






                                share|improve this answer













                                You can't do anything inside the lambda expression you currently have, since that's a Predicate: it returns a boolean. Math.toIntExact returns an int.



                                You can do it without the Math.toIntExact (or a simple cast) like so:



                                return /* create stream, filter */
                                .mapToInt(a -> 1).sum();


                                But this is likely to be slower than doing what you are doing at the moment.







                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Nov 16 '18 at 8:18









                                Andy TurnerAndy Turner

                                84k983143




                                84k983143























                                    3














                                    Yet another option that is not really better - it is possible to use a collector that applies a finisher:



                                    public static int countFriendsStartWithN() {
                                    return friends.stream()
                                    .filter(name -> name.startsWith("N"))
                                    .collect(Collectors.collectingAndThen(Collectors.counting(), Math::toIntExact));
                                    }


                                    This may have an advantage if you need it frequenty - you could build a utility method returning this Collector to make it reusable.






                                    share|improve this answer






























                                      3














                                      Yet another option that is not really better - it is possible to use a collector that applies a finisher:



                                      public static int countFriendsStartWithN() {
                                      return friends.stream()
                                      .filter(name -> name.startsWith("N"))
                                      .collect(Collectors.collectingAndThen(Collectors.counting(), Math::toIntExact));
                                      }


                                      This may have an advantage if you need it frequenty - you could build a utility method returning this Collector to make it reusable.






                                      share|improve this answer




























                                        3












                                        3








                                        3







                                        Yet another option that is not really better - it is possible to use a collector that applies a finisher:



                                        public static int countFriendsStartWithN() {
                                        return friends.stream()
                                        .filter(name -> name.startsWith("N"))
                                        .collect(Collectors.collectingAndThen(Collectors.counting(), Math::toIntExact));
                                        }


                                        This may have an advantage if you need it frequenty - you could build a utility method returning this Collector to make it reusable.






                                        share|improve this answer















                                        Yet another option that is not really better - it is possible to use a collector that applies a finisher:



                                        public static int countFriendsStartWithN() {
                                        return friends.stream()
                                        .filter(name -> name.startsWith("N"))
                                        .collect(Collectors.collectingAndThen(Collectors.counting(), Math::toIntExact));
                                        }


                                        This may have an advantage if you need it frequenty - you could build a utility method returning this Collector to make it reusable.







                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited Nov 16 '18 at 9:01

























                                        answered Nov 16 '18 at 8:56









                                        HulkHulk

                                        3,42812142




                                        3,42812142























                                            2














                                            Here's a way to do this with reduce



                                            public static int countFriendsStartWithN2() {
                                            return friends
                                            .stream()
                                            .filter(name -> name.startsWith("N"))
                                            .map(s -> 1)
                                            .reduce(0, Integer::sum);
                                            }





                                            share|improve this answer




























                                              2














                                              Here's a way to do this with reduce



                                              public static int countFriendsStartWithN2() {
                                              return friends
                                              .stream()
                                              .filter(name -> name.startsWith("N"))
                                              .map(s -> 1)
                                              .reduce(0, Integer::sum);
                                              }





                                              share|improve this answer


























                                                2












                                                2








                                                2







                                                Here's a way to do this with reduce



                                                public static int countFriendsStartWithN2() {
                                                return friends
                                                .stream()
                                                .filter(name -> name.startsWith("N"))
                                                .map(s -> 1)
                                                .reduce(0, Integer::sum);
                                                }





                                                share|improve this answer













                                                Here's a way to do this with reduce



                                                public static int countFriendsStartWithN2() {
                                                return friends
                                                .stream()
                                                .filter(name -> name.startsWith("N"))
                                                .map(s -> 1)
                                                .reduce(0, Integer::sum);
                                                }






                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Nov 16 '18 at 8:25









                                                SamzSakerzSamzSakerz

                                                1,6691627




                                                1,6691627






























                                                    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%2f53333790%2fmath-tointexact-inside-lambda-expression%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

                                                    Bressuire

                                                    Vorschmack

                                                    Quarantine