5 things made easier in Java 9

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.

Create collections

We can now use List.of(), Set.of() and Map.of() to create immutable collections.

1
2
3
4
5
List.of("Hello", "World");
Set.of(1, 2, 3);
Map.of("Hello", 1, "World", 2); // -> Map<String, Integer> with two entries

Use resource references in try-with-resources

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.

1
2
3
4
5
6
public void process() throws IOException {
InputStream inputStream = Files.newInputStream(Paths.get("test.txt"));
try (inputStream) {
inputStream.readAllBytes();
}
}

Convert Optional to Stream

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 Stream of Optionals into a Stream of present value elements.

1
2
3
4
5
6
7
8
9
10
@Test
public void testStream() throws Exception {
final long count = Stream.of(
Optional.of(1),
Optional.empty(),
Optional.of(2)
).flatMap(Optional::stream)
.count();
assertEquals(2, count);
}

Read bytes in InputStream

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.

1
2
final InputStream inputStream = TestInputStream.class.getResourceAsStream("/input.txt");
final String content = new String(this.inputStream.readAllBytes());

Private interface methods

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 sayHi().

1
2
3
4
5
6
7
8
9
10
11
public interface SayHi {
private String buildMessage() {
return "Hello";
}
void sayHi(final String message);
default void sayHi() {
sayHi(buildMessage());
}
}

Check out the book Exploring Java 9 for more new features in Java 9.

Comments