23. Applying indentation

Starting with JDK 12, we can indent text via the String.indent(int n) method.

Let's assume that we have the following String values:

String days = "Sunday
" 
+ "Monday "
+ "Tuesday "
+ "Wednesday "
+ "Thursday "
+ "Friday "
+ "Saturday";

Printing this String values with an indentation of 10 spaces can be done as follows:

System.out.print(days.indent(10));

The output will be as follows:

Now, let's try a cascade indentation:

List<String> days = Arrays.asList("Sunday", "Monday", "Tuesday",
"Wednesday", "Thursday", "Friday", "Saturday");

for (int i = 0; i < days.size(); i++) {
System.out.print(days.get(i).indent(i));
}

The output will be as follows:

Now, let's indent depending on the length of the String value:

days.stream()
.forEachOrdered(d -> System.out.print(d.indent(d.length())));

The output will be as follows:

How about indenting a piece of HTML code? Let's see:

String html = "<html>";
String body = "<body>";
String h2 = "<h2>";
String text = "Hello world!";
String closeH2 = "</h2>";
String closeBody = "</body>";
String closeHtml = "</html>";

System.out.println(html.indent(0) + body.indent(4) + h2.indent(8)
+ text.indent(12) + closeH2.indent(8) + closeBody.indent(4)
+ closeHtml.indent(0));

The output will be as follows:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.2.157