java11新特性简单介绍
本地变量类型推断
public class Client {
public static void main(String[] args) {
var name = "lisi";
System.out.println(name);
List<String> names = Arrays.asList("a", "b", "c");
for (var s : names) {
System.out.println(s);
}
for (var i = 0; i < names.size(); i++) {
System.out.println(names.get(i));
}
}
}
编译器会根据右边的表达式自动推断左边的类型,
var name = "lisi";
String name = "lisi";
这两个声明是一样的。
字符串增强
之前版本的字符串是使用字符数组存储的,新版本换成了字节数组存储,增加了一些新方法
public class Client {
public static void main(String[] args) {
// 判断是否为空白
System.out.println(" ".isBlank());
// 去除左边和右边的空白
System.out.println(" lisi ".strip().length());
// 去除左边的空白
System.out.println(" lisi ".stripLeading().length());
// 去除右边的空白
System.out.println(" lisi ".stripTrailing().length());
// 重复字符串
System.out.println("lisi".repeat(3).length());
// 行数统计
System.out.println("lisi\nlisi\n".lines().count());
}
}
集合增强
List,Set,Map都添加了of和copyOf方法来创建不可变的集合。
public class Client {
public static void main(String[] args) {
List<String> list = List.of("AAA", "BBB");
List<String> copyList = List.copyOf(list);
System.out.println(list == copyList); // true
List<String> a = Arrays.asList("a");
System.out.println(List.copyOf(a) == a); // false
Set<String> set = Set.of("AAA", "BBB");
Set<String> copySet = Set.copyOf(set);
System.out.println(copySet == set);
Map<String, Object> map = Map.of("name", "lisi", "age", 23);
System.out.println(Map.copyOf(map) == map);
System.out.println(Arrays.toString(list.toArray(String[]::new)));
}
}
copyOf的实现原理
// make a copy, short-circuiting based on implementation class
@SuppressWarnings("unchecked")
static <E> List<E> listCopy(Collection<? extends E> coll) {
if (coll instanceof AbstractImmutableList && coll.getClass() != SubList.class) {
return (List<E>)coll;
} else {
return (List<E>)List.of(coll.toArray());
}
}
如果已经是不可变集合,直接返回自身,否则返回一个新的不可变集合。
Collection 新加了一个默认方法toArray(IntFunction)
// JDK11之前
System.out.println(Arrays.toString(list.toArray(new String[0])));
// JDK11
System.out.println(Arrays.toString(list.toArray(String[]::new)));
Stream 增强
public class Client {
public static void main(String[] args) {
// null 就是空stream
System.out.println(Stream.ofNullable(null).count());
List<String> list = List.of("a", "b", "c");
// 截止到第一个不满足条件的元素
list.stream().takeWhile(x -> x.equals("a")).forEach(System.out::println);
System.out.println("==========");
// 从第一个不满足条件的元素开始
list.stream().dropWhile(x -> x.equals("a")).forEach(System.out::println);
System.out.println("==========");
// 迭代 直到不满足条件
Stream.iterate(3, x -> x < 7, x -> x + 1).forEach(System.out::println);
}
}
Optional 增强
public class Client {
public static void main(String[] args) {
Optional.of("abc").or(() -> Optional.of("hello")).stream().forEach(System.out::println);
}
}
增加了or(Supplier<? extends Optional<? extends T>>)和stream()方法
InputStream 增强
public class Client {
public static void main(String[] args) {
try {
try (InputStream is = Client.class.getClassLoader().getResourceAsStream("html.txt");
ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
is.transferTo(baos);
System.out.println(new String(baos.toByteArray()));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
增加了transferTo(OutputStream) 方法,将数据输出到OutputStream。
Http Client API
public class Client {
public static void main(String[] args) throws IOException, InterruptedException {
// 创建http客户端
HttpClient client = HttpClient.newHttpClient();
// 创建GET请求
HttpRequest request = HttpRequest.newBuilder()
.GET()
.uri(URI.create("https://www.baidu.com"))
.build();
// 同步发送请求
System.out.println(client.send(request, HttpResponse.BodyHandlers.ofString()).body());
System.out.println("============");
// 异步发送请求
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.join();
// 创建POST请求
HttpRequest postRequest = HttpRequest.newBuilder()
.uri(URI.create("https://postman-echo.com/post"))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(JSON.toJSONString(Map.of("method", "POST"))))
.build();
System.out.println(client.send(postRequest, HttpResponse.BodyHandlers.ofString()).body());
}
}
java 命令编译运行源码
java Client.java
一个命令编译加运行