编程知识 cdmana.com

What are the new features of Java 9?

Java 17 yes Java The most important one LTS One of the versions , But directly from Java 8 The transition to Java 17 The span is too big , There are bound to be some difficulties . So fat took the time to sort it out from Java 9 To Java 17 Some of the common API The change of . Today, let's take a look at Java 9 There's something .

Java 9

Java 9 The biggest change is the introduction of JShell And modularity , It doesn't use much everyday , So don't spend time on these functions today .

New method for creating collections

Used Google Guava Class libraries know ,Guava Provides static factory methods for creating collections , And can infer generics , for instance :

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

And the original ecology needs all kinds of new To define .Java 9 Improved this situation , 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");

But notice : these API The collections created are immutable (Immutable), You can't add, delete or change these sets .

Stream Expand

Stream API yes Java 8 One of the most important features introduced in . stay Java 9 in Stream Further strengthened .

ofNullable

Stream ofNullable(T t) Returns the order that contains a single element Stream , If it is not empty , Otherwise, it returns empty Stream . This is relatively simple, so I don't give an example .

iterate

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

This is a new iterative implementation for generating finite flows .

  • seed Initial seed value
  • hasNext Used to determine when to end the flow , This with seed of . How this function does not iterate remains seed Calculation , The returned stream may be empty .
  • next The function is used to calculate the value of the next element .

for instance :

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

Equivalent to traditional :

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

takeWhile

Stream.takeWhile(Predicate) Stream Elements in are asserted Predicate, Once the element is asserted as false Just interrupt the operation , Ignore elements without assertions ( The element in the non assertion in time has a condition that meets the condition ), Just return the previously satisfied element .

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

In the above example, only 123.

dropWhile

This API and takeWhile Similar mechanism , Also used to filter Stream The elements in . However, elements that match the assertion will be removed from Stream Remove . Once the element is asserted as false, Will assert as false The element of and the following elements all return .

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

The above example will output 425.

and filter The operation is different , Bear in mind !

Optional Expand

Optional Added three useful API.

  • stream() Optional Now you can turn Stream.
  • ifPresentOrElse(Consumer action, Runnable emptyAction) If there is value, how to spend , No value, how to spend .
  • or(Supplier> supplier) If there is a value, it returns a value Optional, Otherwise, you can get a valuable Optional Channel of (Supplier).

try-with-resources Optimize

stay Java 7 Introduced in try-with-resources function , It ensures that each declared resource will be closed at the end of the statement . Any implementation java.lang.AutoCloseable Object of the interface , And implemented java.io.Closeable Object of the interface , Can be used as resources .

stay Java 7 It needs to be written in this way :

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

And by the Java 9 Simplified as :

BufferedInputStream bufferedInputStream = new BufferedInputStream(System.in);
BufferedInputStream bufferedInputStream1 = new BufferedInputStream(System.in);

try (bufferedInputStream;
bufferedInputStream1) {
// do something
} catch (IOException e) {
e.printStackTrace();
}

Interface private methods

Following Java 8 After introducing interface static method and interface default method , The interface private method is also introduced :

public interface Catable {
/**
* Interface private methods
*/
private void doSomething() {

}
}

introduce HttpClient

Define a new HTTP client API To achieve HTTP/2 and WebSocket, And can replace the old HttpURLConnectionAPI.Java It used to be hard to use native , So was born Apache HttpClientComponents 、OkHttp Wait for the easy-to-use client . The new one is not very easy to use , But it's 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();

Flow

Spring WebFlux Response type Web Framework already 4 Years. , Response flow specification (reactive streams) stay Java 9 It is also initially introduced into JDK in . This thing is still a little advanced , Fat brother hasn't found a specific application scenario yet , Dig a hole first .

summary

Actually Java 9 There are also some underlying optimizations , But for ordinary developers, it's enough to know . The above features , Static invariant sets are commonly used 、try-with-resources Optimize . Other features require your understanding of Java 8 Only when you are very skilled .

The author of this article : Small fat man of minong ,
Link to the original text :https://mp.weixin.qq.com/s/I1sqZfwjsAsLmYh1qdFMBA
The copyright belongs to the author , Please indicate the author of the reprint 、 original text 、 Translators and other source information

版权声明
本文为[Program ape DD]所创,转载请带上原文链接,感谢
https://cdmana.com/2021/10/20211002145752196U.html

Scroll to Top