When talking about the new Java 9 release, many people focus on the Java Platform Module System (JPMS). There are many small changes that can make developer’s life easier in Java 9.
We can now use
Map.of() to create immutable collections.
In Java 9, effectively-final variables can be used in try-with-resources, so it’s no longer required to declare fresh variables for resources managed by this statement. The variable
inputStream is effectively-final, so it can be used directly in the try-with-resources statement.
The new method
Optional.stream() can convert the
Optional into a
Stream. If a value is present, then the result stream contains only the value, otherwise the result stream is empty. This method can work with
flatMap() to convert a
Optionals into a
Stream of present value elements.
In Java 9, three methods are added to
InputStream to easily read and copy data.
readAllBytes() reads all remaining bytes from the input stream.
readNBytes(byte b, int off, int len) reads the given number of bytes from the input stream into the given byte array.
transferTo(OutputStream out) reads all bytes from the input stream and writes to the given output stream.
It’s now possible to add private methods in interfaces in Java 9. The interface
SayHi in the code below has the private method
buildMessage() to generate the default message to use in the default method
Check out the book Exploring Java 9 for more new features in Java 9.