Timeline for Finding count of character occurrences in a string
Current License: CC BY-SA 4.0
11 events
when toggle format | what | by | license | comment | |
---|---|---|---|---|---|
May 10, 2018 at 18:44 | comment | added | tobijdc |
I think with Streams it is more easy to show your intent with how the stream functions are called. Here filter and count make quite clear what is happening, while replace and length might need need more thinking to understand the intent.
|
|
May 3, 2018 at 8:47 | comment | added | JollyJoker | I'd say the main reason to use a stream over a for loop here is to avoid boilerplate code. Even the OPs original code is quicker to read, understand and see that it works as intended. | |
May 2, 2018 at 22:01 | comment | added | Stingy |
@202_accepted But the possibility to short-circuit is not a benefit specific to streams, because you can also short-circuit using a for loop. In fact, due to their nature, streams don't really lend themselves to short-circuiting and similar behavior – Koekje has discovered an example of this today. Sure, there are methods like Stream.limit(long) or Stream.takeWhile(Predicate) , but even there, the documentation mentions how these operations can be costly on ordered parallel streams, because they simply defy the point of parallelism.
|
|
May 2, 2018 at 20:58 | history | edited | Koekje | CC BY-SA 4.0 |
added 468 characters in body
|
May 2, 2018 at 20:47 | comment | added | Koekje | Correct, this also allows us to operate on infinite sequences. @Malachi, I will update my answer in a bit. | |
May 2, 2018 at 20:36 | comment | added | Der Kommissar | @Malachi I seem to recall that streams are also lazy, so it's possible to only partially evaluate the stream. (In this case, we need the whole thing, but we could potentially build a stream that could short-circuit if we only need to know that there are, for example, at least 7 instances.) | |
May 2, 2018 at 20:32 | comment | added | Malachi | Interesting, would you include that with your answer please, for posterity? | |
May 2, 2018 at 20:21 | comment | added | Koekje |
Part subjective, but I like the declarative aspect of it. For me it is very easy to read what it is doing, i.e. count the occurences of a single character in a String . In a lot of cases it is also trivial to parallelize by just calling parallel on the Stream , though I am not sure if it would help much in this case.
|
|
May 2, 2018 at 20:12 | history | edited | Koekje | CC BY-SA 4.0 |
added 85 characters in body
|
May 2, 2018 at 20:12 | comment | added | Malachi |
what are the benefits of a Stream ? I am curious.
|
|
May 2, 2018 at 20:10 | history | answered | Koekje | CC BY-SA 4.0 |