Java 速查表

Java 21 LTS:语法、Stream、Records、虚拟线程、模式匹配

🔍
基本数据类型
int a = 10; long b = 100L; double d = 3.14; boolean flag = true; char c = 'A'; byte by = 127;
8种基本类型:int / long / double / boolean / char / byte / short / float
var list = new ArrayList<String>(); // Java 10+ var map = new HashMap<String, Integer>();
局部变量类型推断 var(Java 10+)
Integer.parseInt("42") String.valueOf(42) Integer.MAX_VALUE // 2147483647
包装类与类型转换
int[] arr = {1, 2, 3}; int[][] matrix = new int[3][4]; Arrays.sort(arr); Arrays.copyOf(arr, 5);
数组声明与常用操作
字符串
String s = "hello"; s.length() // 5 s.toUpperCase() // "HELLO" s.trim() s.strip() // Java 11+ s.isBlank() // Java 11+
常用字符串方法(strip/isBlank 为 Java 11+)
String name = "World"; String msg = "Hello, " + name + "!"; String fmt = String.format("Hello, %s! Age: %d", name, 18); String tmpl = "Hi %s".formatted(name); // Java 15+
字符串拼接与格式化(formatted 为 Java 15+)
// Text Blocks (Java 15+) String json = """ { "name": "Java", "version": 21 } """;
文本块 Text Blocks(Java 15+),适合多行 JSON/SQL/HTML
"hello".contains("ell") // true "hello".startsWith("he") // true "hello".replace("l","r") // "herro" String.join(",","a","b") // "a,b" " hi ".stripLeading() // Java 11+
字符串查找、替换、连接操作
集合框架
// 不可变集合 (Java 9+) List<String> list = List.of("a", "b", "c"); Set<Integer> set = Set.of(1, 2, 3); Map<String,Integer> map = Map.of("a",1,"b",2);
不可变集合 List.of / Set.of / Map.of(Java 9+)
List<String> list = new ArrayList<>(); list.add("x"); list.remove("x"); list.get(0); list.size(); Collections.sort(list); list.sort(Comparator.naturalOrder());
ArrayList 常用操作
Map<String,Integer> map = new HashMap<>(); map.put("a", 1); map.getOrDefault("b", 0); // Java 8+ map.putIfAbsent("c", 3); // Java 8+ map.computeIfAbsent("d", k -> k.length());
HashMap 常用操作(getOrDefault / computeIfAbsent 为 Java 8+)
// SequencedCollection (Java 21+) List<String> seq = new ArrayList<>(List.of("a","b","c")); seq.getFirst(); // "a" seq.getLast(); // "c" seq.addFirst("z"); seq.reversed(); // 反向视图
SequencedCollection:getFirst / getLast / reversed(Java 21+)
Stream API
List<Integer> nums = List.of(1,2,3,4,5); nums.stream() .filter(n -> n % 2 == 0) .map(n -> n * 10) .collect(Collectors.toList());
filter / map / collect 基本链式操作
list.stream().sorted().distinct().limit(3).toList(); // Java 16+ Stream.of("a","b","c").forEach(System.out::println); Stream.iterate(0, n -> n+1).limit(10);
sorted / distinct / limit / toList(toList 为 Java 16+)
int sum = nums.stream().mapToInt(Integer::intValue).sum(); Optional<Integer> max = nums.stream().max(Comparator.naturalOrder()); long count = nums.stream().filter(n -> n > 2).count();
聚合操作:sum / max / count
Map<Boolean,List<Integer>> parts = nums.stream().collect( Collectors.partitioningBy(n -> n % 2 == 0)); String joined = list.stream().collect(Collectors.joining(", "));
分组、分区、joining 收集器
Optional
Optional<String> opt = Optional.of("hello"); Optional<String> empty = Optional.empty(); Optional<String> nullable = Optional.ofNullable(null);
创建 Optional:of / empty / ofNullable
opt.isPresent() // true opt.isEmpty() // false Java 11+ opt.get() // "hello" opt.orElse("default") opt.orElseGet(() -> "computed") opt.orElseThrow() // Java 10+
取值:orElse / orElseGet / orElseThrow(Java 10+)
opt.map(String::toUpperCase) // Optional("HELLO") opt.filter(s -> s.length() > 3) // Optional("hello") opt.ifPresent(System.out::println) opt.ifPresentOrElse( // Java 9+ System.out::println, () -> System.out.println("empty"));
链式操作:map / filter / ifPresentOrElse(Java 9+)
流程控制 & 模式匹配
// Switch Expression (Java 14+) int day = 3; String name = switch (day) { case 1 -> "Monday"; case 2 -> "Tuesday"; case 3 -> "Wednesday"; default -> "Other"; };
Switch 表达式(Java 14+),箭头语法,有返回值
// Pattern Matching instanceof (Java 16+) Object obj = "Hello"; if (obj instanceof String s && s.length() > 3) { System.out.println(s.toUpperCase()); }
instanceof 模式匹配(Java 16+),自动绑定变量
// Pattern Matching Switch (Java 21+) Object o = 42; String result = switch (o) { case Integer i when i > 0 -> "positive: " + i; case Integer i -> "non-positive: " + i; case String s -> "string: " + s; case null -> "null"; default -> "other"; };
Switch 模式匹配(Java 21+),支持 when 守卫和 null
for (int i = 0; i < 10; i++) { ... } for (String s : list) { ... } // for-each while (condition) { ... } do { ... } while (condition);
for / for-each / while / do-while 循环
Record 记录类
// Record (Java 16+) - 不可变数据类 record Point(int x, int y) {} Point p = new Point(3, 4); p.x() // 3 p.y() // 4 p.toString() // "Point[x=3, y=4]"
Record 基础(Java 16+):不可变、自动生成 accessor/equals/toString
record Person(String name, int age) { // 紧凑构造器 Person { if (age < 0) throw new IllegalArgumentException(); name = name.trim(); } // 自定义方法 boolean isAdult() { return age >= 18; } }
紧凑构造器、自定义方法、参数校验
Sealed 密封类
// Sealed Classes (Java 17+) sealed interface Shape permits Circle, Rectangle, Triangle {} record Circle(double radius) implements Shape {} record Rectangle(double w, double h) implements Shape {} final class Triangle implements Shape { ... }
密封类/接口(Java 17+),限定子类范围
// 配合 Pattern Matching Switch double area = switch (shape) { case Circle c -> Math.PI * c.radius() * c.radius(); case Rectangle r -> r.w() * r.h(); case Triangle t -> t.area(); // 无需 default:编译器知道已穷举 };
配合 Switch 模式匹配实现穷举,无需 default
异常处理
try { int r = 10 / 0; } catch (ArithmeticException e) { System.err.println(e.getMessage()); } finally { System.out.println("always runs"); }
try / catch / finally 基本结构
// Multi-catch (Java 7+) try { ... } catch (IOException | SQLException e) { e.printStackTrace(); } // try-with-resources (Java 7+) try (var in = new FileInputStream("f.txt")) { ... }
多异常捕获(Java 7+)、try-with-resources 自动关闭资源
// 自定义异常 class AppException extends RuntimeException { public AppException(String msg) { super(msg); } public AppException(String msg, Throwable cause) { super(msg, cause); } }
自定义异常类
并发
// Virtual Threads (Java 21+) Thread vt = Thread.ofVirtual().start(() -> { System.out.println("virtual thread"); }); // 大量虚拟线程 for (int i = 0; i < 10_000; i++) { Thread.ofVirtual().start(task); }
虚拟线程(Java 21+):轻量级,可创建百万级线程
ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor(); // Java 21+ pool.submit(() -> System.out.println("task")); pool.shutdown(); pool.awaitTermination(10, TimeUnit.SECONDS);
VirtualThreadPerTaskExecutor(Java 21+):每任务一个虚拟线程
CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> "hello") .thenApply(String::toUpperCase) .thenApply(s -> s + "!") .exceptionally(e -> "error"); String result = cf.get(); // "HELLO!"
CompletableFuture 异步链式编程
synchronized (lock) { ... } // 内置锁 ReentrantLock lock = new ReentrantLock(); lock.lock(); try { ... } finally { lock.unlock(); } AtomicInteger counter = new AtomicInteger(); counter.incrementAndGet();
synchronized / ReentrantLock / AtomicInteger
文件 I/O
Path p = Path.of("file.txt"); // Java 11+ Files.writeString(p, "hello"); // Java 11+ String s = Files.readString(p); // Java 11+ List<String> lines = Files.readAllLines(p); Files.exists(p); Files.delete(p);
Files API(Java 11+):readString / writeString / readAllLines
Files.walk(Path.of("./src")) .filter(f -> f.toString().endsWith(".java")) .forEach(System.out::println); Files.copy(src, dst, StandardCopyOption.REPLACE_EXISTING); Files.createDirectories(Path.of("a/b/c"));
Files.walk 递归遍历目录、copy、createDirectories
构建工具与命令
mvn compile # 编译 mvn test # 运行测试 mvn package # 打包 jar mvn install # 安装到本地仓库 mvn spring-boot:run # 运行 Spring Boot
Maven 常用命令
./gradlew build # 构建 ./gradlew test # 运行测试 ./gradlew bootRun # 运行 Spring Boot ./gradlew dependencies # 查看依赖树 java -jar app.jar # 运行 jar
Gradle 常用命令
java --version # 查看版本 javac Main.java # 编译单文件 java Main # 运行 java --enable-preview Main # 开启预览特性 jshell # 交互式 REPL
Java 命令行:编译、运行、REPL