Features in Java 11

Posted By :Harshit Verma |29th June 2019

Some of them you definitely know such as the responsive Http2/API, you can run source code directly without compiling. However, have you tried extensions of the common classes such as String, Optional, Collections and Files, and if you haven’t already, congratulations, you’ll learn about some of them in this article.

 

1. LOCAL PARAMETER TYPE INFERENCE FOR LAMBDA EXPRESSIONS

JDK 11 allows var keyword to be used when declaring formal parameters of  the implicitly typed lambda expressions:

Function<String, String> append = (var string) -> string + " World";
String appendedString = append.apply("Hello");
System.out.println(appendedString);

It’s not just adding var keyword to a variable that omits the type. The JDK 11 also allow annotations to be added to the lambda’s parameters without having to write the full variable type name. Let’s take a look at with example:

Function<String, String> append = (@NonNull var string) -> string + " World";
String appendedString = append.apply("Hello");
System.out.println(appendedString);
// Output of above program
Hello World


2. USAGE OF THE STRING:: REPEAT METHOD TO COPY A STRING

from JDK 11, we have a repeat method, that does exactly what we will need.

var str = "abc";
var repeated = str.repeat(3);
System.out.println(repeated);
// Output of above program
abcabcabc

 


3. CREATE A PATH WITH PATH::OF METHOD

I really like Path API, which solves the problem of switching between the paths, URIs, URLs, and FILEs. In Java 11 we can use the Paths::get and Path::of methods to make them very uniform.

Path googlePath = Path.of(URI.create("www.google.com"))
Path studentFilePath = Path.of("/home/Students/student.txt")

 

4. FILES::READSTRING AND FILES::WRITESTRING FOR FILE READING AND WRITING

If you need to read content from a very large file, we generally use the lines method which returns a lazy stream. Similarly, if you want to store content in the file at the same time, I usually write to the files using the write method by passing an Iterable.
 
But in JDK 11, two methods of reading and writeString have been added to the Files class.

String studentFileContent = Files.readString(Path.of("student.txt"))
String modifiedStudentContent = addNewSubject(studentFileContent)
Files.writeString(Path.of("student-mod.txt"),modifiedStudentContent)


5. STRING::LINES TO GET THE NUMBER OF DATA ROWS

You have the multi-line string and you want to do a separate operation for each line. You can do this with the String::lines method.

String studentFileContent = Files.readString(Path.of("student.txt"))
String modifiedStudentContent = addNewSubject(studentFileContent)
Files.writeString(Path.of("student-mod.txt"),modifiedStudentContent)

The lines in the Stream are in order in which they occur in the string. Unlike split, the new lines method is lazy.

 

6. USAGE OF OPTIONAL::ISEMPTY INSTEAD OF ISPRESENT
Almost in every application, we need to check that if a value exists or not and for that, we often use the Optional::isPresent method. I know! there is no problem in writing that, but writing does not understand the meaning of well. Now if we need to check that the value is empty inside the Optional::isPresent method then we add the ! operator at the front.

val optional: Optional<String> = Optional.empty()
if(!optional.isPresent)
    // value is empty
This ! is easily forgotten on the Optional starting with Java 11, we have a better solution.

val optional: Optional<String> = Optional.empty()
    if (optional.isEmpty) {
        //  value is empty
    }
 

The isEmpty method is used to return the true if the value is not present.


7. HANDLING REGULAR EXPRESSIONS WITH PATTERN::ASMATCHPREDICATE

You have the regular expression and want to do some filtering based on it. What do you do?

Pattern<String> chracterPredicate = Pattern.compile("ah").asPredicate();
Stream.of("coding","ahsan","infinite")
       .filter(chracterPredicate)
       .forEach(System.out::println);
// Output of above program
ahsan

We had asPredicate method as part of JDK 8, which will create a Predicate if and only if a given Pattern is found in a given string.

In JDK 11 we have another method Pattern::asMatchPredicate. So, what is the difference between them:

-> asPredicate: Under the hood, the asPredicate method called  matcher(s).find().
-> asMatchPredicate: It will checks if a entire string conforms to this regular expression. This method behaves like matcher(s).matches().

 


About Author

Harshit Verma

Harshit is a bright Web Developer with expertise in Java and Spring framework and ORM tools Hibernate.

Request For Proposal

[contact-form-7 404 "Not Found"]

Ready to innovate ? Let's get in touch

Chat With Us