package fun.psgame.test;
import org.junit.jupiter.api.Test;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.RecordComponent;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.NumberFormat;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class MainTest {
@Test
public void m100() throws Exception {
Class<String> clazz = String.class;
clazz.getDeclaredConstructor().newInstance();
}
// ============================ JDK17↓ ============================
@Test
public void m23() {
}
// ============================ JDK16↓ ============================
// ============================ JDK15↓ ============================
// 只允许特定类继承
private sealed class Student permits ZhangSan, LiSi {
}
private final class ZhangSan extends Student {
}
private final class LiSi extends Student {
}
// ============================ JDK14↓ ============================
@Test
public void m22() {
// 多行调用时的空指针提示更加友好
List<List<String>> list = new ArrayList<>();
list.add(new ArrayList<>());
list.get(0).add(null);
// java.lang.NullPointerException: Cannot invoke "String.length()" because the return value of "java.util.List.get(int)" is null
System.out.println(list.get(0).get(0).length());
}
@Test
public void m21() {
MyRecord myRecord = new MyRecord(1L, "Hello");
System.out.println(myRecord.id());
System.out.println(myRecord.name);
boolean isRecord = MyRecord.class.isRecord();
RecordComponent[] recordComponents = MyRecord.class.getRecordComponents();
for (RecordComponent recordComponent : recordComponents) {
System.out.println(recordComponent.getName());
}
}
private record MyRecord(Long id, String name) {
// 静态变量
public static String STATIC_VALUE = "";
// 静态方法
public static String staticMethod() {
return "";
}
static {
// 静态代码块
System.out.println("静态代码块");
}
public MyRecord {
// 构造代码块
System.out.println("构造代码块");
}
}
@Test
public void m20() {
Object obj;
if (new Random().nextBoolean()) {
obj = "Hello";
} else {
obj = 123;
}
// 模式匹配
if (obj instanceof String str) {
System.out.println(str);
}
}
// ============================ JDK13↓ ============================
@Test
public void m19() {
// switch可以返回值
int i = ThreadLocalRandom.current().nextInt(0,3);
var str = switch (i) {
case 0 -> {
// 代码块使用yield返回
yield "0";
}
case 1 -> "1";
default -> "";
};
System.out.println(str);
}
@Test
public void m18() {
// 文本块
String html = """
<html>
<body>
<p>Hello, World</p>
</body>
</html>
""";
String json = """
{
"name":"mkyong",
"age":38
}
""";
System.out.println(html);
System.out.println(json);
}
// ============================ JDK12↓ ============================
@Test
public void m17() {
// 创建紧凑数字表示形式
NumberFormat formatter = NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT);
NumberFormat formatter1 = NumberFormat.getCompactNumberInstance(Locale.CHINA, NumberFormat.Style.SHORT);
String formattedString = formatter.format(25000L);
String formattedString1 = formatter1.format(25000L);
System.out.println(formattedString);
System.out.println(formattedString1);
}
@Test
public void m16() throws Exception {
// 对比两个文件是否相同,返回第一个不匹配的字节的位置,两个文件相同返回-1
Files.mismatch(Paths.get(""), Paths.get(""));
}
@Test
public void m15() {
// transform方法(类似map?)
Integer transform = "A".transform(s -> 1);
}
@Test
public void m14() {
// 缩进,参数为缩进字符数
String result = "foo\nbar\nbar2".indent(4);
System.out.println(result);
}
@Test
public void m13() {
int i = ThreadLocalRandom.current().nextInt(1, 5);
// switch语句增强
switch (i) {
case 1, 2 -> System.out.println("1, 2");
case 3 -> System.out.println("3");
case 4 -> {
System.out.println("4");
}
default -> System.out.println("default");
}
}
// ============================ JDK11↓ ============================
@Test
public void m12() throws Exception {
// HttpClient jdk9引入,11正式可用
var request = HttpRequest.newBuilder()
.uri(URI.create("https://javastack.cn"))
.GET()
.build();
var client = HttpClient.newHttpClient();
// 同步
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
// 异步
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println);
}
@Test
public void m11() throws Exception {
var classLoader = ClassLoader.getSystemClassLoader();
var inputStream = classLoader.getResourceAsStream("javastack.txt");
var javastack = File.createTempFile("javastack2", "txt");
try (var outputStream = new FileOutputStream(javastack)) {
assert inputStream != null;
// inputStream添加transferTo方法,可以直接写出到输入流
inputStream.transferTo(outputStream);
}
}
@Test
public void m10() {
// 判断字符串是否为空白
System.out.println(" ".isBlank());// true
// 去除首尾空格
// trim无法删除掉Unicode空白字符,strip可以
System.out.println(" Javastack ".strip());// "Javastack"
"".trim();
// 去除尾部空格
System.out.println(" Javastack ".stripTrailing());// " Javastack"
// 去除首部空格
System.out.println(" Javastack ".stripLeading());// "Javastack "
// 复制字符串
System.out.println("Java".repeat(3));// "JavaJavaJava"
// 行数统计
System.out.println("A\nB\nC".lines().count());// 3
}
// ============================ JDK10↓ ============================
@Test
public void m9() {
List<String> list = new ArrayList<>();
// Collectors新增不可变集合收集器
list.stream()
.collect(Collectors.toUnmodifiableList());
list.stream()
.collect(Collectors.toUnmodifiableSet());
list.stream()
.collect(Collectors.toUnmodifiableMap(Function.identity(), String::length));
}
@Test
public void m8() {
// 新增copyOf静态方法,返回不可变集合
List<String> list = List.copyOf(new ArrayList<>());
Set<String> set = Set.copyOf(list);
Map<String, Object> map = Map.copyOf(new HashMap<>());
}
@Test
public void m7() {
// 类型推断
var str = "Hello";
var list1 = new ArrayList<String>();
//局部变量初始化
var list = new ArrayList<String>();
//for循环内部索引变量
for (var s : list) {
System.out.println(s);
}
//传统的for循环声明变量
for (var i = 0; i < list.size(); i++) {
System.out.println(i);
}
}
// ============================ JDK9↓ ============================
@Test
public void m6() {
// 不允许使用下划线作为变量名
// String _ = "";
}
/**
* 继Java 8 引入了接口静态方法和接口默认方法后,又引入了接口私有方法
*/
private interface MyInterface {
// 接口私有方法
private void method() {
System.out.println("private method");
}
}
@Test
public void m5() {
// jdk9之前
try (BufferedInputStream bufferedInputStream = new BufferedInputStream(System.in);
BufferedInputStream bufferedInputStream1 = new BufferedInputStream(System.in)) {
// do something
} catch (IOException e) {
e.printStackTrace();
}
// jdk9之后
BufferedInputStream bufferedInputStream = new BufferedInputStream(System.in);
BufferedInputStream bufferedInputStream1 = new BufferedInputStream(System.in);
try (bufferedInputStream;
bufferedInputStream1) {
// do something
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void m4() {
Optional.of("A")
.stream()// optional可以stream了
.forEach(System.out::println);
Optional.ofNullable(null)
.ifPresentOrElse(System.out::println, () -> System.out.println("not present"));// optional没有值时做什么
Optional.ofNullable(null)
.or(() -> Optional.of("B"))// optional有值就用其值,没有值就用提供的Supplier
.ifPresent(System.out::println);
}
@Test
public void m3() {
Stream.of(1, 2, 3, 4, 2, 5)
.takeWhile(x -> x < 4)// 取数据直到
.forEach(System.out::println);
System.out.println();
Stream.of(1, 2, 3, 4, 2, 5)
.dropWhile(x -> x < 4)// 丢数据直到
.forEach(System.out::println);
}
@Test
public void m2() {
Stream.iterate(0, i -> i < 3, i -> i + 1)
.forEach(System.out::println);
// 相当于
for (int i = 0; i < 5; ++i) {
System.out.println(i);
}
}
@Test
public void m1() {
// 可以使用静态方法创建集合
List<String> list = List.of("A", "B");
// 但是集合不可变
// list.add("C");
Set<String> set = Set.of("A", "B");
Map<String, String> map = Map.of("A", "B");
}
}