6.3 Java代码示例
java
复制代码
import java.util.*;
import java.util.stream.*;

public class ModernJavaDemo {
    
    // 记录类型(Java 16+)
    public record Person(String name, int age) {}
    
    // 密封接口(Java 17+)
    public sealed interface Shape 
        permits Circle, Rectangle {}
    
    public record Circle(double radius) implements Shape {}
    public record Rectangle(double width, double height) implements Shape {}
    
    public static void main(String[] args) {
        List<Person> people = List.of(
            new Person("Alice", 30),
            new Person("Bob", 25),
            new Person("Charlie", 35)
        );
        
        // Stream API 和 Lambda 表达式(Java 8+)
        var averageAge = people.stream()
            .filter(p -> p.age() > 20)
            .mapToInt(Person::age)
            .average()
            .orElse(0);
        
        System.out.println("Average age: " + averageAge);
        
        // 模式匹配(Java 21+)
        Shape shape = new Circle(5.0);
        String description = switch (shape) {
            case Circle c -> "Circle with radius " + c.radius();
            case Rectangle r -> "Rectangle " + r.width() + "x" + r.height();
        };
        
        System.out.println(description);
        
        // 虚拟线程(Java 21+)
        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
            executor.submit(() -> System.out.println("Running on virtual thread"));
        }
    }
}