I am not sure I agree that a for
loop is more elegant per se. The downside of your method compared to a traditional for
loop is that it requires a bit more processing most of the time, because you need to create a new character buffer and put the replacements in there, and you create a new String
object.
I would probably create an initial implementation with a Java 8 Stream
, e.g.:
String string = "hello";
char letter = 'l';
long count = string.chars().filter(character -> character == letter).count();
To me this is probably more elegant than a traditional for
loop. With Stream
s it is possible to write it in a declarative way. In a lot of cases they are also trivial to parallelize, requiring only a parallel
function call on the Stream
. Furthermore, they are lazy which means the processing can stop early, only the necessary data will be processed. Note that in this case, we have to process each element (each character), so it makes no difference here.