1

Is there a better way of doing this in Java8 e.g. with Stream.of(...)?

if (messageBody.startsWith("\n\n")) {
    messageBody = messageBody.replaceFirst("\n", "");
}
final String messageBodyFormatted = messageBody.replaceAll("\n", "<br />");
3
  • 5
    You can get rid of the condition by using: replaceFirst("\n(?=\n)", "");. I don't think Java 8 will give you more here. Commented Aug 22, 2016 at 11:01
  • Does this mean you want to leave heading/trailing spaces (not newlines) untouched? Commented Aug 22, 2016 at 11:37
  • 1
    @Maroun Maroun: that doesn’t have the same semantics as the startsWith check which requires the occurrence to be at the very start of the string. Fixing that, allows an even simpler solution: replaceFirst("^\n\n", "\n"). Commented Aug 22, 2016 at 13:27

1 Answer 1

3

Here’s an option:

    if (messageBody.startsWith("\n\n")) {
        messageBody = messageBody.substring(1); // remove first newline
    }
    final String messageBodyFormatted = messageBody.replace("\n", "<br />");

Inside the if statement I’m simply removing the first char since I already know what it is. If you think it’s subtle, just use your own version instead. I changed the final replaceAll() with replace() — in spite of the name it does the same, only without regular expressions.

Sign up to request clarification or add additional context in comments.

3 Comments

Indeed the box of java 8 need not be opened.
@JoopEggen, I agree. Streams are fun, but I wouldn’t dream of using them in this snippet.
The only thing different in Java 8 would be using Optionals in lieu of if-statements, and even then, it's only appealing if you really don't like to define variables: Optional.of(messageBody).map(body -> body.startsWith("\n\n") ? body.substring(1) : body).map(body -> body.replace("\n", "<br />")).ifPresent(formatted -> { /* do something*/ })

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.