JDK 16: The new features in Java 11

New String Methods

Java 11 adds a few new methods to the String classisBlanklinesstripstripLeadingstripTrailing, and repeat.

Let’s see how we can make use of the new methods to extract non-blank, stripped lines from a multi-line string:

String multilineString = "online study guru helps \n \n developers \n explore Java.";
List<String> lines = multilineString.lines()
  .filter(line -> !line.isBlank())
  .map(String::strip)
  .collect(Collectors.toList());
assertThat(lines).containsExactly("online study gurus", "developers", "explore Java.");

These methods can reduce the amount of boilerplate involved in manipulating string objects, and save us from having to import libraries.

New File Methods

Additionally, it’s now easier to read and write Strings from files.

We can use the new readString and writeString static methods from the Files class:

Path filePath = Files.writeString(Files.createTempFile(tempDir, "demo", ".txt"), "Sample text");
String fileContent = Files.readString(filePath);
assertThat(fileContent).isEqualTo("Sample text");

Collection to an Array

The java.util.Collection interface contains a new default toArray method which takes an IntFunction argument.

This makes it easier to create an array of the right type from a collection:

List sampleList = Arrays.asList(“Java”, “Kotlin”); String[] sampleArray = sampleList.toArray(String[]::new); assertThat(sampleArray).containsExactly(“Java”, “Kotlin”);

he Not Predicate Method

A static not method has been added to the Predicate interface. We can use it to negate an existing predicate, much like the negate method:

List<String> sampleList = Arrays.asList("Java", "\n \n", "Kotlin", " ");
List withoutBlanks = sampleList.stream()
  .filter(Predicate.not(String::isBlank))
  .collect(Collectors.toList());
assertThat(withoutBlanks).containsExactly("Java", "Kotlin");

While not(isBlank) reads more naturally than isBlank.negate(), the big advantage is that we can also use not with method references, like not(String:isBlank).

Local-Variable Syntax for Lambda

Support for using the local variable syntax (var keyword) in lambda parameters was added in Java 11.

We can make use of this feature to apply modifiers to our local variables, like defining a type annotation:

List<String> sampleList = Arrays.asList("Java", "Kotlin");
String resultString = sampleList.stream()
  .map((@Nonnull var x) -> x.toUpperCase())
  .collect(Collectors.joining(", "));
assertThat(resultString).isEqualTo("JAVA, KOTLIN");

Author: Susheel kumar

Leave a Reply

Your email address will not be published. Required fields are marked *