Skip to content

Commit 06872dc

Browse files
committed
feat: 增加 Java 21 新特性示例代码
1 parent dd7f782 commit 06872dc

11 files changed

Lines changed: 284 additions & 2 deletions

File tree

core-java-modules/core-java-20/src/main/java/JEP431Test.java

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99
/**
1010
* JDK 21 之前,顺序集合中操作体验不一致
1111
* @author https://www.wdbyte.com
12-
* @date 2023/10/12ø
1312
*/
1413
public class JEP431Test {
1514
public static void main(String[] args) {
@@ -58,6 +57,5 @@ public static void main(String[] args) {
5857
System.out.println();
5958

6059
// sortedSet linkedHashMap 逆序输出很难操作
61-
6260
}
6361
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
## Java 21 新特性示例
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5+
<modelVersion>4.0.0</modelVersion>
6+
<parent>
7+
<groupId>com.wdbyte.core-java-modules</groupId>
8+
<artifactId>core-java-modules</artifactId>
9+
<version>1.0.0-SNAPSHOT</version>
10+
</parent>
11+
12+
<groupId>com.wdbyte.jdk21</groupId>
13+
<artifactId>core-java-21</artifactId>
14+
15+
<properties>
16+
<maven.compiler.source>21</maven.compiler.source>
17+
<maven.compiler.target>21</maven.compiler.target>
18+
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
19+
</properties>
20+
21+
</project>
Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
import java.time.LocalDate;
2+
import java.util.FormatProcessor;
3+
import java.util.Locale;
4+
5+
/**
6+
* 字符串模版
7+
*
8+
* @author https://www.wdbyte.com
9+
* @date 2023/10/13
10+
*/
11+
public class Jep430StringTemplate {
12+
13+
public static void main(String[] args) {
14+
int x = 20;
15+
int y = 3;
16+
String s = x + " + " + y + " = " + (x + y);
17+
System.out.println(s);
18+
19+
String sb = new StringBuilder().append(x).append(" + ").append(y).append(" = ").append(x + y).toString();
20+
System.out.println(sb);
21+
22+
23+
String sFormat = String.format("%d + %d = %d", x, y, x + y);
24+
System.out.println(sFormat);
25+
26+
System.out.println("--------------------");
27+
28+
// JDK 21 使用字符串模版 STR 进行插值
29+
String sTemplate = StringTemplate.STR."\{x} + \{y} = \{x+y}";
30+
System.out.println(sTemplate);
31+
32+
// 字符串模版也可以先定义模版,再处理插值
33+
StringTemplate st = StringTemplate.RAW."\{x} + \{y} = \{x+y}";
34+
String sTemplate2 = StringTemplate.STR.process(st);
35+
System.out.println(sTemplate2);
36+
37+
System.out.println("--------------------");
38+
LocalDate now = LocalDate.now();
39+
String nowStr = StringTemplate.STR."现在是 \{now.getYear()} 年 \{now.getMonthValue()} 月 \{now.getDayOfMonth()} 号";
40+
System.out.println(nowStr);
41+
42+
// 字符串模版读取数组,字符串模版也可以嵌套
43+
String[] infoArr = { "Hello", "Java 21", "https://www.wdbyte.com" };
44+
String sArray = StringTemplate.STR."\{infoArr[0]}, \{STR."\{infoArr[1]}, \{infoArr[2]}"}";
45+
System.out.println(sArray);
46+
47+
// 字符串模版也可以结合多行文本
48+
String name = "https://www.wdbyte.com";
49+
String address = "程序猿阿朗";
50+
String json = StringTemplate.STR."""
51+
{
52+
"name": "\{name}",
53+
"address": "\{address}"
54+
}
55+
""";
56+
System.out.println(json);
57+
System.out.println("--------------------");
58+
59+
}
60+
}
61+
62+
63+
record Rectangle(String name, double width, double height) {
64+
double area() {
65+
return width * height;
66+
}
67+
}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import java.util.ArrayDeque;
2+
import java.util.ArrayList;
3+
import java.util.Deque;
4+
import java.util.LinkedHashMap;
5+
import java.util.LinkedHashSet;
6+
import java.util.List;
7+
import java.util.SequencedCollection;
8+
import java.util.TreeSet;
9+
import java.util.function.Consumer;
10+
11+
/**
12+
* @author https://www.wdbyte.com
13+
* @date 2023/10/12
14+
*/
15+
public class Jep431SequencedCollection {
16+
public static void main(String[] args) {
17+
// JDK 21 之后,为所有元素插入有序集合提供了一致的操作 API
18+
List<Integer> listTemp = List.of(1, 2, 3, 4, 5);
19+
20+
ArrayList<Integer> list = new ArrayList(listTemp);
21+
Deque<Integer> deque = new ArrayDeque<>(listTemp);
22+
LinkedHashSet<Integer> linkedHashSet = new LinkedHashSet<>(listTemp);
23+
TreeSet<Integer> sortedSet = new TreeSet<>(listTemp);
24+
LinkedHashMap<Integer, Integer> linkedHashMap = new LinkedHashMap<>();
25+
for (int i = 1; i <= 5; i++) {
26+
linkedHashMap.put(i, i);
27+
}
28+
29+
// 输出第一个元素
30+
System.out.println(list.getFirst());
31+
System.out.println(deque.getFirst());
32+
System.out.println(linkedHashSet.getFirst());
33+
System.out.println(sortedSet.getFirst());
34+
System.out.println(linkedHashMap.firstEntry());
35+
System.out.println("-----------------------");
36+
37+
// 输出最后一个元素
38+
System.out.println(list.getLast());
39+
System.out.println(list.getLast());
40+
System.out.println(deque.getLast());
41+
System.out.println(sortedSet.getLast());
42+
System.out.println(linkedHashMap.lastEntry());
43+
System.out.println("-----------------------");
44+
45+
// 逆序遍历
46+
Consumer<SequencedCollection> printFn = s -> {
47+
// reversed 逆序元素
48+
s.reversed().forEach(System.out::print);
49+
System.out.println();
50+
};
51+
printFn.accept(list);
52+
printFn.accept(deque);
53+
printFn.accept(linkedHashSet);
54+
printFn.accept(sortedSet);
55+
// 有序 map 接口是 SequencedMap,上面的 consume类型不适用
56+
linkedHashMap.reversed().forEach((k, v) -> {
57+
System.out.print(k);
58+
});
59+
}
60+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* @author https://www.wdbyte.com
3+
* @date 2023/10/13
4+
*/
5+
public class Jep440Record {
6+
public static void main(String[] args) {
7+
8+
Object obj = "Hello www.wdbyte.com";
9+
if (obj instanceof String s) {
10+
System.out.println(s);
11+
}
12+
13+
Dog dog = new Dog("Husky", 1);
14+
if (dog instanceof Dog(String name, int age)) {
15+
String res = StringTemplate.STR."name:\{name} age:\{age}";
16+
System.out.println(res);
17+
}
18+
Object myDog = new MyDog(dog, Color.BLACK);
19+
if (myDog instanceof MyDog(Dog(String name,int age),Color color)){
20+
String res = StringTemplate.STR."name:\{name} age:\{age} color:\{color}";
21+
System.out.println(res);
22+
}
23+
}
24+
}
25+
26+
record Dog(String name, int age) {}
27+
enum Color{WHITE,GREY,BLACK};
28+
record MyDog(Dog dog,Color color){};
29+
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* @author https://www.wdbyte.com
3+
* @date 2023/10/13
4+
*/
5+
public class Jep441SwitchPatten {
6+
7+
public static void main(String[] args) {
8+
String r1 = formatterPatternSwitch(Integer.valueOf(1));
9+
String r2 = formatterPatternSwitch(new String("www.wdbyte.com"));
10+
String r3 = formatterPatternSwitch(Double.valueOf(3.14D));
11+
System.out.println(r1);
12+
System.out.println(r2);
13+
System.out.println(r3);
14+
}
15+
16+
static String formatterPatternSwitch(Object obj) {
17+
return switch (obj) {
18+
case Integer i -> String.format("int %d", i);
19+
case Long l -> String.format("long %d", l);
20+
case Double d -> String.format("double %f", d);
21+
case String s -> String.format("String %s", s);
22+
default -> obj.toString();
23+
};
24+
}
25+
26+
static void testFooBarNew(String s) {
27+
switch (s) {
28+
case null -> System.out.println("Oops");
29+
case "Foo", "Bar" -> System.out.println("Great");
30+
default -> System.out.println("Ok");
31+
}
32+
}
33+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import java.util.List;
2+
3+
/**
4+
* @author https://www.wdbyte.com
5+
* @date 2023/10/15
6+
*/
7+
public class Jep443Unname {
8+
9+
public static void main(String[] args) {
10+
String _ = "123213";
11+
Integer _ = 123;
12+
List<Integer> list = List.of(1, 2, 3, 4, 5, 6, 7, 8);
13+
int count = 0;
14+
for (Integer _ : list) {
15+
count++;
16+
}
17+
System.out.println(count);
18+
}
19+
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import java.time.Duration;
2+
import java.util.concurrent.Executors;
3+
import java.util.stream.IntStream;
4+
5+
/**
6+
* 虚拟线程
7+
*
8+
* @author https://www.wdbyte.com
9+
* @date 2023/10/10
10+
*/
11+
public class Jep444VirtualThread {
12+
public static void main(String[] args) throws InterruptedException {
13+
// 创建并提交执行虚拟线程
14+
long start = System.currentTimeMillis();
15+
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
16+
IntStream.range(0, 10_000).forEach(i -> {
17+
executor.submit(() -> {
18+
Thread.sleep(Duration.ofSeconds(1));
19+
return i;
20+
});
21+
});
22+
}
23+
System.out.println("time:" + (System.currentTimeMillis() - start) + "ms");
24+
25+
26+
// 创建一个虚拟线程指定虚拟线程名称
27+
Thread thread1 = Thread.ofVirtual().name("v-thread").unstarted(() -> {
28+
String threadName = Thread.currentThread().getName();
29+
System.out.println(String.format("[%s] Hello Virtual Thread", threadName));
30+
});
31+
thread1.start();
32+
System.out.println(thread1.isVirtual());
33+
34+
//创建一个线程,启动为虚拟线程
35+
Thread thread2 = new Thread(() -> {
36+
String threadName = Thread.currentThread().getName();
37+
System.out.println(String.format("[%s] Hello Virtual Thread 2", threadName));
38+
});
39+
40+
Thread.startVirtualThread(thread2);
41+
42+
// 判断一个线程是否是虚拟线程
43+
System.out.println(thread1.isVirtual());
44+
System.out.println(thread2.isVirtual());
45+
46+
Thread.sleep(1000);
47+
}
48+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
2+
void main(){
3+
System.out.println("Hello, Java 21!");
4+
}
5+

0 commit comments

Comments
 (0)