Local Var
在Lambda表達式中,可以使用var關鍵字來標識變量,變量類型由編譯器自行推斷。
例如:
// LocalVar.java
package com.itranswarp.jdk11;
import java.util.Arrays;
public class LocalVar {
public static void main(String[] args) {
Arrays.asList("Java", "Python", "Ruby")
.forEach((var s) -> {
System.out.println("Hello, " + s);
});
}
}
HttpClient
長期以來,如果要訪問Http資源,JDK的標準庫中只有一個HttpURLConnection,這個古老的API使用非常麻煩,而且已經(jīng)不適用于最新的HTTP協(xié)議。
JDK11的新的HttpClient支持HTTP/2和WebSocket,并且可以使用異步接口:
// HttpApi.java
package com.itranswarp.jdk11;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.CompletableFuture;
public class HttpApi {
public static void main(String[] args) {
HttpRequest request = HttpRequest.newBuilder().uri(URI.create("https://www.qq.com/")).GET().build();
HttpResponse.BodyHandler<String> bodyHandler = HttpResponse.BodyHandlers.ofString();
HttpClient client = HttpClient.newHttpClient();
CompletableFuture<HttpResponse<String>> future = client.sendAsync(request, bodyHandler);
future.thenApply(HttpResponse::body).thenAccept(System.out::println).join();
}
}
List API
對于List接口,新增了一個of(T...)接口,用于快速創(chuàng)建List對象:
List<String> list = List.of("Java", "Python", "Ruby");
List的toArray()還新增了一個重載方法,可以更方便地把List轉換為數(shù)組??梢员容^一下兩種轉換方法:
// 舊的方法:傳入String[]:
String[] oldway = list.toArray(new String[list.size()]);
// 新的方法:傳入IntFunction:
String[] newway = list.toArray(String[]::new);
讀寫文件
對Files類增加了writeString和readString兩個靜態(tài)方法,可以直接把String寫入文件,或者把整個文件讀出為一個String:
Files.writeString(
Path.of("./", "tmp.txt"), // 路徑
"hello, jdk11 files api", // 內(nèi)容
StandardCharsets.UTF_8); // 編碼
String s = Files.readString(
Paths.get("./tmp.txt"), // 路徑
StandardCharsets.UTF_8); // 編碼
這兩個方法可以大大簡化讀取配置文件之類的問題。
String API
String新增了strip()方法,和trim()相比,strip()可以去掉Unicode空格,例如,中文空格:
String s = " Hello, JDK11!\u3000\u3000";
System.out.println(" original: [" + s + "]");
System.out.println(" trim: [" + s.trim() + "]");
System.out.println(" strip: [" + s.strip() + "]");
System.out.println(" stripLeading: [" + s.stripLeading() + "]");
System.out.println("stripTrailing: [" + s.stripTrailing() + "]");
輸出如下:
original: [ Hello, JDK11! ]
trim: [Hello, JDK11! ]
strip: [Hello, JDK11!]
stripLeading: [Hello, JDK11! ]
stripTrailing: [ Hello, JDK11!]
新增isBlank()方法,可判斷字符串是不是“空白”字符串:
String s = " \u3000"; // 由一個空格和一個中文空格構成
System.out.println(s.isEmpty()); // false
System.out.println(s.isBlank()); // true
新增lines()方法,可以非常方便地按行分割字符串:
String s = "Java\nPython\nRuby";
s.lines().forEach(System.out::println);
新增repeat()方法,可以指定重復次數(shù):
System.out.println("-".repeat(10)); // 打印----------
除了新增的API外,JDK11還帶來了EpsilonGC,就是什么也不做的GC,以及ZGC,一個幾乎可以做到毫秒級暫停的GC。ZGC還處于實驗階段,所以啟動它需要命令行參數(shù)-XX:+UnlockExperimentalVMOptions -XX:+UseZGC。