DEV Community

Discussion on: How can I improve this while loop code snippet?

Collapse
 
kspeakman profile image
Kasey Speakman • Edited

(I don't use Java, but) I'd probably use the Java Streams API.

Optional<int> whitespaceIndex =
    IntStream.range(0, this.source.length())
        .filter(i -> Character.isWhiteSpace(this.source.charAt(i)))
        .findFirst();
Optional<char> whitespaceChar = whitespaceIndex.map(i -> this.source.charAt(i));

Using Optional makes it obvious you have to handle when whitespace is not found.

Note: not guaranteed to compile.