Java 8 Stream, get string length due to several conditionsDoes a finally block always get executed in Java?How do I read / convert an InputStream into a String in Java?How do I create a Java string from the contents of a file?How to get an enum value from a string value in Java?Get current stack trace in JavaHow to split a string in JavaConverting 'ArrayList<String> to 'String[]' in JavaGetting the Current Working Directory in JavaHow do I convert a String to an int in Java?How to Convert a Java 8 Stream to an Array?

Why was the Spitfire's elliptical wing almost uncopied by other aircraft of World War 2?

Is it idiomatic to construct against `this`

Phrase for the opposite of "foolproof"

How to pronounce 'c++' in Spanish

Is there any official lore on the Far Realm?

On The Origin of Dissonant Chords

How could Tony Stark make this in Endgame?

Pre-plastic human skin alternative

What happens to Mjolnir (Thor's hammer) at the end of Endgame?

How does Captain America channel this power?

How would 10 generations of living underground change the human body?

Re-entry to Germany after vacation using blue card

Two field separators (colon and space) in awk

Why do games have consumables?

A ​Note ​on ​N!

Apply MapThread to all but one variable

Checks user level and limit the data before saving it to mongoDB

Why does Mind Blank stop the Feeblemind spell?

Minor Revision with suggestion of an alternative proof by reviewer

"Whatever a Russian does, they end up making the Kalashnikov gun"? Are there any similar proverbs in English?

What is causing the white spot to appear in some of my pictures

555 timer FM transmitter

What is the most expensive material in the world that could be used to create Pun-Pun's lute?

Do I have an "anti-research" personality?



Java 8 Stream, get string length due to several conditions


Does a finally block always get executed in Java?How do I read / convert an InputStream into a String in Java?How do I create a Java string from the contents of a file?How to get an enum value from a string value in Java?Get current stack trace in JavaHow to split a string in JavaConverting 'ArrayList<String> to 'String[]' in JavaGetting the Current Working Directory in JavaHow do I convert a String to an int in Java?How to Convert a Java 8 Stream to an Array?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I have a program that calculate the occurrences of d, for example s = "dda" and n = 10 I will repeat those until I get s.length = 10 e.g ddaddaddad the result = 7d.



I have done this in basics loop:



int count = 0;
String s = "dda";
int n = 10;
for (int i = 0; i < s.length(); i++)
if (s.charAt(i) == 'd')
count++;


for (int i = 0; i < n % s.length(); i++)
if (s.charAt(i) == 'd')
count++;

return count * (n / s.length());


Thus I'm trying to do that using streams, and I'm wondering how I can do it?



What I already achieved:



return s.chars().filter(x -> x == 'd').count() * (n / s.length()) + (n % s.length());


I know The problem in that last part (n % s.length()) I need to check if the index contain d or not, but I don't know how to do that.










share|improve this question






























    1















    I have a program that calculate the occurrences of d, for example s = "dda" and n = 10 I will repeat those until I get s.length = 10 e.g ddaddaddad the result = 7d.



    I have done this in basics loop:



    int count = 0;
    String s = "dda";
    int n = 10;
    for (int i = 0; i < s.length(); i++)
    if (s.charAt(i) == 'd')
    count++;


    for (int i = 0; i < n % s.length(); i++)
    if (s.charAt(i) == 'd')
    count++;

    return count * (n / s.length());


    Thus I'm trying to do that using streams, and I'm wondering how I can do it?



    What I already achieved:



    return s.chars().filter(x -> x == 'd').count() * (n / s.length()) + (n % s.length());


    I know The problem in that last part (n % s.length()) I need to check if the index contain d or not, but I don't know how to do that.










    share|improve this question


























      1












      1








      1








      I have a program that calculate the occurrences of d, for example s = "dda" and n = 10 I will repeat those until I get s.length = 10 e.g ddaddaddad the result = 7d.



      I have done this in basics loop:



      int count = 0;
      String s = "dda";
      int n = 10;
      for (int i = 0; i < s.length(); i++)
      if (s.charAt(i) == 'd')
      count++;


      for (int i = 0; i < n % s.length(); i++)
      if (s.charAt(i) == 'd')
      count++;

      return count * (n / s.length());


      Thus I'm trying to do that using streams, and I'm wondering how I can do it?



      What I already achieved:



      return s.chars().filter(x -> x == 'd').count() * (n / s.length()) + (n % s.length());


      I know The problem in that last part (n % s.length()) I need to check if the index contain d or not, but I don't know how to do that.










      share|improve this question
















      I have a program that calculate the occurrences of d, for example s = "dda" and n = 10 I will repeat those until I get s.length = 10 e.g ddaddaddad the result = 7d.



      I have done this in basics loop:



      int count = 0;
      String s = "dda";
      int n = 10;
      for (int i = 0; i < s.length(); i++)
      if (s.charAt(i) == 'd')
      count++;


      for (int i = 0; i < n % s.length(); i++)
      if (s.charAt(i) == 'd')
      count++;

      return count * (n / s.length());


      Thus I'm trying to do that using streams, and I'm wondering how I can do it?



      What I already achieved:



      return s.chars().filter(x -> x == 'd').count() * (n / s.length()) + (n % s.length());


      I know The problem in that last part (n % s.length()) I need to check if the index contain d or not, but I don't know how to do that.







      java loops java-stream






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 9 at 9:17







      Ibrahim Ali

















      asked Mar 9 at 9:09









      Ibrahim AliIbrahim Ali

      13812




      13812






















          2 Answers
          2






          active

          oldest

          votes


















          2














          all you need to add to your calculation is to substring s by the reminder and repeat the count: -



           return s.chars().filter(x -> x == 'd').count() * (n / s.length()) +
          s.substring(0, n % s.length()).chars().filter(x -> x == 'd').count();


          EDIT: if, for some reason, you dislike the oldfashined substring, you could replace it with stream of ints from 0 to the reminder:



           return s.chars().filter(x -> x == 'd').count() * (n / s.length()) +
          IntStream.range(0, n % s.length()).filter(i -> s.charAt(i)== 'd').count();


          However, the question reminas whether this all-stream version is more comprehensive/readable.






          share|improve this answer

























          • I'm was thinking that I can do that without substring, e.g some methods in stream, anyway thanks.

            – Ibrahim Ali
            Mar 9 at 9:52











          • @IbrahimAli, see my edited answer

            – Sharon Ben Asher
            Mar 9 at 10:08


















          0














          You might just be looking for a simpler logic if I get your question right. It could be as :



          private int characterCountWithRecurrenceWithinLimit(String string, int limit, char c) 
          // repeat string unless its shorter than the limit

          StringBuilder sBuilder = new StringBuilder(string);
          while (sBuilder.length() < limit)
          sBuilder.append(string);

          // keep the string within the limit
          String repeatedString = sBuilder.toString().substring(0, limit);
          // count the character occurrence
          return (int) IntStream.range(0, repeatedString.length())
          .filter(i -> repeatedString.charAt(i) == c)
          .count();






          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%2f55075732%2fjava-8-stream-get-string-length-due-to-several-conditions%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









            2














            all you need to add to your calculation is to substring s by the reminder and repeat the count: -



             return s.chars().filter(x -> x == 'd').count() * (n / s.length()) +
            s.substring(0, n % s.length()).chars().filter(x -> x == 'd').count();


            EDIT: if, for some reason, you dislike the oldfashined substring, you could replace it with stream of ints from 0 to the reminder:



             return s.chars().filter(x -> x == 'd').count() * (n / s.length()) +
            IntStream.range(0, n % s.length()).filter(i -> s.charAt(i)== 'd').count();


            However, the question reminas whether this all-stream version is more comprehensive/readable.






            share|improve this answer

























            • I'm was thinking that I can do that without substring, e.g some methods in stream, anyway thanks.

              – Ibrahim Ali
              Mar 9 at 9:52











            • @IbrahimAli, see my edited answer

              – Sharon Ben Asher
              Mar 9 at 10:08















            2














            all you need to add to your calculation is to substring s by the reminder and repeat the count: -



             return s.chars().filter(x -> x == 'd').count() * (n / s.length()) +
            s.substring(0, n % s.length()).chars().filter(x -> x == 'd').count();


            EDIT: if, for some reason, you dislike the oldfashined substring, you could replace it with stream of ints from 0 to the reminder:



             return s.chars().filter(x -> x == 'd').count() * (n / s.length()) +
            IntStream.range(0, n % s.length()).filter(i -> s.charAt(i)== 'd').count();


            However, the question reminas whether this all-stream version is more comprehensive/readable.






            share|improve this answer

























            • I'm was thinking that I can do that without substring, e.g some methods in stream, anyway thanks.

              – Ibrahim Ali
              Mar 9 at 9:52











            • @IbrahimAli, see my edited answer

              – Sharon Ben Asher
              Mar 9 at 10:08













            2












            2








            2







            all you need to add to your calculation is to substring s by the reminder and repeat the count: -



             return s.chars().filter(x -> x == 'd').count() * (n / s.length()) +
            s.substring(0, n % s.length()).chars().filter(x -> x == 'd').count();


            EDIT: if, for some reason, you dislike the oldfashined substring, you could replace it with stream of ints from 0 to the reminder:



             return s.chars().filter(x -> x == 'd').count() * (n / s.length()) +
            IntStream.range(0, n % s.length()).filter(i -> s.charAt(i)== 'd').count();


            However, the question reminas whether this all-stream version is more comprehensive/readable.






            share|improve this answer















            all you need to add to your calculation is to substring s by the reminder and repeat the count: -



             return s.chars().filter(x -> x == 'd').count() * (n / s.length()) +
            s.substring(0, n % s.length()).chars().filter(x -> x == 'd').count();


            EDIT: if, for some reason, you dislike the oldfashined substring, you could replace it with stream of ints from 0 to the reminder:



             return s.chars().filter(x -> x == 'd').count() * (n / s.length()) +
            IntStream.range(0, n % s.length()).filter(i -> s.charAt(i)== 'd').count();


            However, the question reminas whether this all-stream version is more comprehensive/readable.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 9 at 10:07

























            answered Mar 9 at 9:27









            Sharon Ben AsherSharon Ben Asher

            9,59932037




            9,59932037












            • I'm was thinking that I can do that without substring, e.g some methods in stream, anyway thanks.

              – Ibrahim Ali
              Mar 9 at 9:52











            • @IbrahimAli, see my edited answer

              – Sharon Ben Asher
              Mar 9 at 10:08

















            • I'm was thinking that I can do that without substring, e.g some methods in stream, anyway thanks.

              – Ibrahim Ali
              Mar 9 at 9:52











            • @IbrahimAli, see my edited answer

              – Sharon Ben Asher
              Mar 9 at 10:08
















            I'm was thinking that I can do that without substring, e.g some methods in stream, anyway thanks.

            – Ibrahim Ali
            Mar 9 at 9:52





            I'm was thinking that I can do that without substring, e.g some methods in stream, anyway thanks.

            – Ibrahim Ali
            Mar 9 at 9:52













            @IbrahimAli, see my edited answer

            – Sharon Ben Asher
            Mar 9 at 10:08





            @IbrahimAli, see my edited answer

            – Sharon Ben Asher
            Mar 9 at 10:08













            0














            You might just be looking for a simpler logic if I get your question right. It could be as :



            private int characterCountWithRecurrenceWithinLimit(String string, int limit, char c) 
            // repeat string unless its shorter than the limit

            StringBuilder sBuilder = new StringBuilder(string);
            while (sBuilder.length() < limit)
            sBuilder.append(string);

            // keep the string within the limit
            String repeatedString = sBuilder.toString().substring(0, limit);
            // count the character occurrence
            return (int) IntStream.range(0, repeatedString.length())
            .filter(i -> repeatedString.charAt(i) == c)
            .count();






            share|improve this answer



























              0














              You might just be looking for a simpler logic if I get your question right. It could be as :



              private int characterCountWithRecurrenceWithinLimit(String string, int limit, char c) 
              // repeat string unless its shorter than the limit

              StringBuilder sBuilder = new StringBuilder(string);
              while (sBuilder.length() < limit)
              sBuilder.append(string);

              // keep the string within the limit
              String repeatedString = sBuilder.toString().substring(0, limit);
              // count the character occurrence
              return (int) IntStream.range(0, repeatedString.length())
              .filter(i -> repeatedString.charAt(i) == c)
              .count();






              share|improve this answer

























                0












                0








                0







                You might just be looking for a simpler logic if I get your question right. It could be as :



                private int characterCountWithRecurrenceWithinLimit(String string, int limit, char c) 
                // repeat string unless its shorter than the limit

                StringBuilder sBuilder = new StringBuilder(string);
                while (sBuilder.length() < limit)
                sBuilder.append(string);

                // keep the string within the limit
                String repeatedString = sBuilder.toString().substring(0, limit);
                // count the character occurrence
                return (int) IntStream.range(0, repeatedString.length())
                .filter(i -> repeatedString.charAt(i) == c)
                .count();






                share|improve this answer













                You might just be looking for a simpler logic if I get your question right. It could be as :



                private int characterCountWithRecurrenceWithinLimit(String string, int limit, char c) 
                // repeat string unless its shorter than the limit

                StringBuilder sBuilder = new StringBuilder(string);
                while (sBuilder.length() < limit)
                sBuilder.append(string);

                // keep the string within the limit
                String repeatedString = sBuilder.toString().substring(0, limit);
                // count the character occurrence
                return (int) IntStream.range(0, repeatedString.length())
                .filter(i -> repeatedString.charAt(i) == c)
                .count();







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 9 at 9:20









                NamanNaman

                46.4k12104206




                46.4k12104206



























                    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%2f55075732%2fjava-8-stream-get-string-length-due-to-several-conditions%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

                    Save data to MySQL database using ExtJS and PHP [closed]2019 Community Moderator ElectionHow can I prevent SQL injection in PHP?Which MySQL data type to use for storing boolean valuesPHP: Delete an element from an arrayHow do I connect to a MySQL Database in Python?Should I use the datetime or timestamp data type in MySQL?How to get a list of MySQL user accountsHow Do You Parse and Process HTML/XML in PHP?Reference — What does this symbol mean in PHP?How does PHP 'foreach' actually work?Why shouldn't I use mysql_* functions in PHP?

                    Compiling GNU Global with universal-ctags support Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Tags for Emacs: Relationship between etags, ebrowse, cscope, GNU Global and exuberant ctagsVim and Ctags tips and trickscscope or ctags why choose one over the other?scons and ctagsctags cannot open option file “.ctags”Adding tag scopes in universal-ctagsShould I use Universal-ctags?Universal ctags on WindowsHow do I install GNU Global with universal ctags support using Homebrew?Universal ctags with emacsHow to highlight ctags generated by Universal Ctags in Vim?

                    Add ONERROR event to image from jsp tldHow to add an image to a JPanel?Saving image from PHP URLHTML img scalingCheck if an image is loaded (no errors) with jQueryHow to force an <img> to take up width, even if the image is not loadedHow do I populate hidden form field with a value set in Spring ControllerStyling Raw elements Generated from JSP tagds with Jquery MobileLimit resizing of images with explicitly set width and height attributeserror TLD use in a jsp fileJsp tld files cannot be resolved