Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

This article also participated in the “Digitalstar Project” to win a creative gift package and creative incentive money

Java 17 is one of the most important LTS releases of Java, but the jump from Java 8 to Java 17 is too big to be easy. So He took the time to review some of the common API changes from Java 9 to Java 17. Today’s first look at what Java 9 has in store.

Java 9

One of the biggest changes in Java 9 is the introduction of a JShell and modularity, which I don’t use much on a daily basis, so I don’t spend time on these features today.

New way to create collections

Those of you who have used the Google Guava library know that Guava provides static factory methods for creating collections and the ability to infer generics, for example:

 List<Person> list = Lists.newArrayList();
 Map<KeyType, Person> map = Maps.newLinkedHashMap();
Copy the code

And primitive ecology needs all kinds of new definition. Java 9 improves this situation and now you can:

 // [1, 2, 3, 4]
 List<Integer> integers = List.of(1, 2, 3, 4);
 // {1,2,3}
 Set<Integer> integerSet = Set.of(1, 2, 3);
 // {"hello":"world","hi":"java"}
 Map<String, String> hello = Map.of("hello", "world", "hi", "java");
Copy the code

Note, however, that the collections created by these apis are Immutable, and you cannot add, delete, or modify them.

The Stream extension

The Stream API is one of the most important features introduced in Java 8. Stream has been further enhanced in Java 9.

ofNullable

Stream

ofNullable(T T) Returns a sequential Stream containing a single element, if not null, otherwise null. I’m not going to give you an example because this is a little bit easier.

iterate

 Stream<T> iterate(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next)
Copy the code

This is a new iterative implementation that generates a finite stream.

  • seedInitial seed value
  • hasNextUsed to determine when to end a streamseedThe relevant. How is this function not iterated reservedseedThe returned stream may be empty.
  • nextThe function evaluates the next element.

Here’s an example:

 Stream.iterate(0, i -> i < 5, i -> i + 1)
   .forEach(System.out::println);
Copy the code

Equivalent to traditional:

 for (int i = 0; i < 5; ++i) {
     System.out.println(i);
 }
 ​
Copy the code

takeWhile

Stream. TakeWhile (Predicate) elements in a Stream are Predicate. Once the Predicate is false, the Predicate is interrupted.

 Stream.of(1, 2, 3, 4, 2, 5)
         .takeWhile(x -> x < 4)
         .forEach(System.out::println);
Copy the code

In the example above, only 1, 2, 3 will be printed.

dropWhile

Similar to the takeWhile mechanism, this API is also used to filter elements in a Stream. However, elements that match the assertion are removed from the Stream. Once the element is asserted to false, all elements that are asserted to false and subsequent elements are returned.

 Stream.of(1, 2, 3, 4, 2, 5)
         .dropWhile(x -> x < 4)
         .forEach(System.out::println);
Copy the code

The above example prints 4, 2, 5.

And filter operation is not the same ah, remember!

Optional extensions

Optional adds three useful apis.

  • stream() OptionalNow I can turnStream.
  • ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction)How to consume if there is value, how to consume if there is no value.
  • or(Supplier<? extends Optional<? extends T>> supplier)If it has a value, it returns a valueOptionalOtherwise, provide a value that can be retrievedOptionalThe channel (Supplier).

The try – with – resources optimization

The try-with-Resources feature introduced in Java 7 ensures that each declared resource is closed at the end of a statement. Any object that implements the java.lang.AutoCloseable interface, and any object that implements the java.io.Closeable interface, can be used as a resource.

For Java 7, you need to write:

try (BufferedInputStream bufferedInputStream = new BufferedInputStream(System.in); BufferedInputStream bufferedInputStream1 = new BufferedInputStream(System.in)) { // do something } catch (IOException e)  { e.printStackTrace(); }Copy the code

With Java 9, this simplifies to:

 BufferedInputStream bufferedInputStream = new BufferedInputStream(System.in);
 BufferedInputStream bufferedInputStream1 = new BufferedInputStream(System.in);
 ​
 try (bufferedInputStream;
      bufferedInputStream1) {
     // do something
 } catch (IOException e) {
     e.printStackTrace();
 }
Copy the code

Interface private methods

Following the introduction of interface static methods and interface default methods in Java 8, interface private methods were introduced:

Public interface Catable {/** * private void doSomething() {}}Copy the code

The introduction of HttpClient

Define a new HTTP client API to implement HTTP/2 and WebSocket, and replace the old HttpURLConnectionAPI. Java used to be really difficult to use native, so Apache HttpClientComponents, OkHttp and other good clients were born. The new one doesn’t work very well, but it’s going from zero to one.

 HttpRequest httpRequest = HttpRequest.newBuilder(newURI)
         .header("Content-Type","*/*")
         .GET()
         .build();
 HttpClient httpClient = HttpClient.newBuilder()
         .connectTimeout(Duration.of(10, ChronoUnit.SECONDS))
         .version(HttpClient.Version.HTTP_2)
         .build();
Copy the code

Flow

The Spring WebFlux Responsive Web framework is now four years old, and Reactive Streams specification was initially introduced into the JDK in Java 9. This thing is still a little advanced, fat brother has not found the specific application scenario, first dig a hole.

conclusion

There are some low-level optimizations in Java 9, but that’s enough for the average developer to know. Static invariant sets and try-with-resources optimization are the most commonly used of these features. The rest of the features will be great if you are very familiar with Java 8.