Java basic characteristic reading series -Java11

Java11 is a LTS version after Java8. Java8 of LTS will expire this year, after Java8, Java11 is the best choice. New features Java9 to Java11 although not span Java8, but in the virtual machine level has been greatly upgraded. By Benjamin of this blog, we look Java11 any different.


Java11 utilization rate is not high, there are still a lot of people use Java8 in a production environment. This article will use examples to explain Java9 into Java11 most important new features. This article uses the code to explain the new features, there will be a large section of text.

Local variable type inference

Java 10 There is a new keyword var, when a local variable declaration vardoes not need to specify the particular data type (local variable refers to the method of variables declared in).

In 10 previous versions of Java, you need to declare variables:

String text = "Hello Java 9";
复制代码

In Java 10, you can use varan alternative String. The compiler to infer the type of a variable based on variable assignment. In the following example textthe type is String:

var text = "Hello Java 10";
复制代码

By varvariable declaration remains static type. Another type can not be assigned to the variables already. The following piece of code will not compile by:

var text = "Hello Java 11";
text = 23;
复制代码

Can finalbe prevented declared varvariables are repeated assignment:

final var text = "Banana";
text = "Joe"; // 编译报错
复制代码

varVariables must be assigned a value type of clear, for no assignment or the compiler can not infer the type of a variable, it will compile error. The following code will not compile:

var a;
var nothing = null;
var lambda = () -> System.out.println("Pity!");
var method = this::someMethod;
复制代码

Local type inference when dealing with very generic code. In the following example, currentthe type Map<String, List<Integer>>, if used varinstead Map<String, List<Integer>>, can be much less sample code:

var myList = new ArrayList<Map<String, List<Integer>>>();
for (var current : myList) {
    System.out.println(current);
}
复制代码

In the Java 11 varit can also be used for parameter lambda, but need to add @Nullableannotations:

Predicate<String> predicate = (@Nullable var a ) -> true;
复制代码

Tip: In Intellij IDEA in, you can select a variable, press CMD/CTRLto show the true type of a variable (keyboard can be used for party CTRL + J).

HTTP Client

Java 9Hidden in a new processing API Http request HttpClient. To Java11this API has been perfect, and in the JDK java.netunder the package. Take a look at the API can do something about it.

This new HttpClientcan be synchronous or asynchronous use. Synchronous request will block the current thread until the response is returned. BodyHandlersIt defines the expected return data type. (eg string, file or byte array):

var request = HttpRequest.newBuilder()
                   .uri(URI.create("https://winterbe.com"))
                   .GET()
                   .build();
var client = HttpClient.newHttpClient();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
复制代码

The same request can be processed asynchronously. Call sendAsyncdoes not block the current thread and a return CompleteFutureto build a pipeline asynchronous operation.

var request = HttpRequest.newBuilder()
                   .uri(URI.create("https://winterbe.com"))
                   .build();
var client = HttpClient.newHttpClient();
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println);
复制代码

It may be omitted .GET(), the default is the request method.

By the following example POSTto a method of URLtransmitting data. BodyHandlersType can also be used to define the data needs to send a request, such as strings , byte array , a file or input stream :

var request = HttpRequest.newBuilder()
                   .uri(URI.create("https://postman-echo.com/post"))
                   .header("Content-Type", "text/plain")
                   .POST(HttpRequest.BodyPublishers.ofString("Hi there!"))
                   .build();
var client = HttpClient.newHttpClient();
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());      // 200
复制代码

The last example demonstrates how BASIC-AUTHto authenticate:

var request = HttpRequest.newBuilder()
    .uri(URI.create("https://postman-echo.com/basic-auth"))
    .build();
var client = HttpClient.newBuilder()
    .authenticator(new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("postman", "password".toCharArray());
        }
    })
    .build();
var response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode());      // 200
复制代码

Collections

Java in containers such as List, Set, Maphas expanded a lot of new ways. List.ofWill create a new parameter based on immutable list, List.copyit created this listimmutable copy.

var list = List.of("A", "B", "C");
var copy = List.copyOf(List);
System.out.println(list == copy); // true
复制代码

Because listalready are immutable, no need to create another instance when copying, so lisiand copypoints to the same instance. However, if you want to copy a variable object, you'll create a new instance to ensure that changes to the original object does not affect the copied object.

var list = new ArrayList<String>();
var copy = List.copyOf(list);
System.out.println(list == copy);
复制代码

When creating immutable map when objects do not need to manually create a map, only need to use Map.ofthe method and alternate key value can be passed.

var map = Map.of("A", 1, "B", 2);
System.out.println(map);
复制代码

No change in the API Java 11 immutable container. However, if you attempt to add an immutable container or reduction elements, it will throw java.lang.UnsupportedOperationExceptionan exception. Fortunately, Intellij IDEAit will issue a warning when you try to modify an immutable container.

Streams

StreamsIn Java8 added new features added in the back and three new methods. Stream.ofNullableThe method to construct the flow through a single element:

Stream.ofNullable(null)
         .count();  // 0
复制代码

dropWhileAnd the takeWhilemethod can accept a predicateparameter to decide whether to comply with the conditions of the elements cleared out from the stream.

It is a predicate function programming interface

Optionals

OptionalsAlso receives some pretty useful methods. Optinals example, can now be transformed into simple stream or returned to another optional standby an empty optional.

Optional.of("foo").orElseThrow();     // foo
Optional.of("foo").stream().count();  // 1
Optional.ofNullable(null)
    .or(() -> Optional.of("fallback"))
    .get();                           // fallback
复制代码

Strings

String The base class also added a number of check blanks and a method for calculating the number of lines of the string.

" ".isBlank();                // true
" Foo Bar ".strip();          // "Foo Bar"
" Foo Bar ".stripTrailing();  // " Foo Bar"
" Foo Bar ".stripLeading();   // "Foo Bar "
"Java".repeat(3);             // "JavaJavaJava"
"A\nB\nC".lines().count();    // 3
复制代码

InputStreams

Finally, a brief talk about InputStreamprovides a very helpful way to transfer data to OutputStream, the following example in the original data transmission time can often see.

var classLoader = ClassLoader.getSystemClassLoader();
var inputStream = classLoader.getResourceAsStream("myFile.txt");
var tempFile = File.createTempFile("myFileCopy", "txt");
try (var outputStream = new FileOutputStream(tempFile)) {
    inputStream.transferTo(outputStream);
}
复制代码

Other characteristics of the JVM

Above these things I think Java8 to Java11 the most interesting new features. But the new features far more than that. The following features in the latest versions of Java are:

The next step

Many people (including me) still use Java8 in a production environment. However, by the year 2020, Java8 of TLS over. So now it is a good opportunity to migrate to the Java11. I wrote a migration guide to help you migrate from Java8 to Java11. At the same time you should also read my Java8 and Stream API tutorial to learn how to use a more fashionable way of development. These have been published to the source on GitHub, and casually play (if you like, tap the star).

(Finish)

original

No micro-channel public attention, something else to talk

Guess you like

Origin juejin.im/post/5dd0bdd96fb9a02000262307