Saturday, July 28, 2018

Java 11 String new methods with examples

In this blog post, We are going to learn the six new methods added to String class in Java 11. 

JDK 11 features - Strings


Java 11 Version added few more methods to the string class. This method helps the developer to simply the coding styles and improve performance

lines() Method

Returns the Stream of strings separated with a line break from multi-line strings
Syntax

Stream<String> lines()
Stream lines = string.lines();



This method can be rewritten in the older version using the stream as below

String linesExample= string.lines()
.map(String::trim)
.collect(joining("\n"));

Example

Trim() method is not Unicode aware compliant

String multilinesstring="String\\nlines\\ndemo\\n";
multilinesstring.lines().forEach(System.out::println); // returns String lines demo

strip() method


This method removes Unicode whitespace character from a string. This has also the same behavior like trim() method.

Trim() method is not Unicode aware compliant
System.out.println(" cloud".strip()); // prints "cloud"
System.out.println("hadoop ".strip()); // prints "hadoop"
System.out.println(" cloudhadoop ".strip()); // prints "cloudhadoop"


stringLeading() method


This method removes a leading whitespace character from String

stringTrailing() method

This method removes a trailing whitespace character from String.

stringTrailing+stringLeading is equal to strip() method.

isBlank() Method


This method is used to check if the string is empty or only contains whitespace characters

repeat(int) method

return the number of times the string want to repeat. number of times can be configured as a parameter to this method

Related article