🚀 JDK 8 (2014年3月) – 重大更新

1. Lambda表达式

// 传统写法
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
Collections.sort(names, new Comparator<String>() {
    @Override
    public int compare(String a, String b) {
        return a.compareTo(b);
    }
});

// Lambda表达式
Collections.sort(names, (a, b) -> a.compareTo(b));
// 或者更简洁
Collections.sort(names, String::compareTo);

2. Stream API

List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David");
List<String> result = names.stream()
    .filter(name -> name.length() > 3)
    .map(String::toUpperCase)
    .sorted()
    .collect(Collectors.toList());
// 结果: [ALICE, CHARLIE, DAVID]

3. 方法引用

// 静态方法引用
List<String> strings = Arrays.asList("1", "2", "3");
List<Integer> numbers = strings.stream()
    .map(Integer::parseInt)
    .collect(Collectors.toList());

// 实例方法引用
List<String> names = Arrays.asList("alice", "bob");
names.forEach(System.out::println);

4. 默认方法 (Default Methods)

interface Vehicle {
    void start();
    
    default void honk() {
        System.out.println("Beep!");
    }
}

class Car implements Vehicle {
    @Override
    public void start() {
        System.out.println("Car started");
    }
    // 不需要实现honk方法
}

5. Optional类

public Optional<String> findUserName(int id) {
    if (id > 0) {
        return Optional.of("User" + id);
    }
    return Optional.empty();
}

// 使用
findUserName(1)
    .map(String::toUpperCase)
    .ifPresent(System.out::println);

findUserName(-1)
    .orElse("Unknown User");

优点: 函数式编程支持、代码更简洁、避免空指针异常、提高开发效率


JDK 9 (2017年9月) – 重大更新

1. 模块系统 (Project Jigsaw)

// module-info.java
module my.module {
    requires java.base;
    requires java.logging;
    exports com.example.api;
}

2. JShell (Java REPL)

jshell
jshell> int x = 5
x ==> 5
jshell> x * 2
$2 ==> 10

3. 集合工厂方法

// 不可变集合
List<String> list = List.of("a", "b", "c");
Set<String> set = Set.of("x", "y", "z");
Map<String, Integer> map = Map.of("one", 1, "two", 2);

4. Stream API增强

// takeWhile
Stream.of(1, 2, 3, 4, 5, 6)
    .takeWhile(n -> n < 4)
    .forEach(System.out::println); // 1, 2, 3

// dropWhile
Stream.of(1, 2, 3, 4, 5, 6)
    .dropWhile(n -> n < 4)
    .forEach(System.out::println); // 4, 5, 6

优点: 模块化提升安全性和性能、交互式编程、不可变集合安全性


JDK 10 (2018年3月)

1. var关键字 (局部变量类型推断)

var list = new ArrayList<String>();
var map = new HashMap<String, Integer>();
var result = "Hello World";

// 在循环中使用
for (var item : list) {
    System.out.println(item);
}

2. G1垃圾收集器改进

  • 并行Full GC
  • 减少停顿时间

优点: 代码更简洁、减少冗余类型声明、垃圾收集性能提升


JDK 11 (2018年9月) – LTS版本

1. HTTP客户端API

HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
    .uri(URI.create("https://api.example.com/data"))
    .header("Content-Type", "application/json")
    .GET()
    .build();

HttpResponse<String> response = client.send(request, 
    HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());

2. 字符串新方法

String text = "  Hello World  ";
System.out.println(text.strip());        // "Hello World"
System.out.println(text.stripLeading()); // "Hello World  "
System.out.println(text.stripTrailing());// "  Hello World"
System.out.println(text.isBlank());      // false
System.out.println("".isBlank());        // true

String multiline = "Line1\nLine2\nLine3";
multiline.lines().forEach(System.out::println);

3. 文件操作增强

Path path = Paths.get("example.txt");
String content = Files.readString(path);
Files.writeString(path, "New content", StandardOpenOption.CREATE);

优点: 标准化HTTP客户端、字符串处理更方便、文件操作简化


JDK 12 (2019年3月)

1. Switch表达式 (预览)

// 传统switch
String result;
switch (day) {
    case MONDAY:
    case FRIDAY:
    case SUNDAY:
        result = "Weekend";
        break;
    case TUESDAY:
        result = "Weekday";
        break;
    default:
        result = "Unknown";
}

// 新的switch表达式
String result = switch (day) {
    case MONDAY, FRIDAY, SUNDAY -> "Weekend";
    case TUESDAY -> "Weekday";
    default -> "Unknown";
};

优点: Switch表达式更简洁、减少错误


JDK 13 (2019年9月)

1. 文本块 (预览)

// 传统写法
String html = "<html>\n" +
              "    <body>\n" +
              "        <h1>Hello World</h1>\n" +
              "    </body>\n" +
              "</html>";

// 文本块
String html = """
              <html>
                  <body>
                      <h1>Hello World</h1>
                  </body>
              </html>
              """;

2. Switch表达式改进

int result = switch (value) {
    case 1, 2, 3 -> {
        System.out.println("Small number");
        yield value * 2;
    }
    case 4, 5, 6 -> value * 3;
    default -> 0;
};

优点: 多行字符串更易读、Switch表达式功能完善


JDK 14 (2020年3月)

1. Records (预览)

// 传统类
public class Person {
    private final String name;
    private final int age;
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    // getter、equals、hashCode、toString方法...
}

// Record
public record Person(String name, int age) {}

// 使用
Person person = new Person("Alice", 30);
System.out.println(person.name()); // Alice
System.out.println(person);        // Person[name=Alice, age=30]

2. Pattern Matching for instanceof (预览)

// 传统写法
if (obj instanceof String) {
    String str = (String) obj;
    System.out.println(str.length());
}

// Pattern Matching
if (obj instanceof String str) {
    System.out.println(str.length());
}

3. Helpful NullPointerExceptions

// 更详细的空指针异常信息
String name = person.getAddress().getStreet().getName();
// 异常: Cannot invoke "Street.getName()" because the return value of "Address.getStreet()" is null

优点: Record减少样板代码、模式匹配简化类型检查、异常信息更清晰


JDK 15 (2020年9月)

1. 文本块 (正式)

String json = """
              {
                  "name": "John",
                  "age": 30,
                  "city": "New York"
              }
              """;

2. Sealed Classes (预览)

public sealed class Shape 
    permits Circle, Rectangle, Triangle {
}

public final class Circle extends Shape {
    private final double radius;
    // ...
}

public final class Rectangle extends Shape {
    private final double width, height;
    // ...
}

优点: 密封类提供更好的继承控制、文本块正式可用


JDK 16 (2021年3月)

1. Records (正式)

public record Point(int x, int y) {
    // 紧凑构造器
    public Point {
        if (x < 0 || y < 0) {
            throw new IllegalArgumentException("Coordinates must be positive");
        }
    }
    
    // 静态方法
    public static Point origin() {
        return new Point(0, 0);
    }
}

2. Pattern Matching for instanceof (正式)

public void processObject(Object obj) {
    if (obj instanceof String str && str.length() > 5) {
        System.out.println("Long string: " + str.toUpperCase());
    } else if (obj instanceof Integer num && num > 0) {
        System.out.println("Positive number: " + num);
    }
}

优点: Records正式可用、模式匹配正式版本


JDK 17 (2021年9月) – LTS版本 🌟

1. Sealed Classes (正式)

public sealed class Vehicle 
    permits Car, Truck, Motorcycle {
}

public final class Car extends Vehicle {
    private String model;
    // ...
}

public non-sealed class Truck extends Vehicle {
    // 允许进一步继承
}

2. Pattern Matching增强

public String getObjectInfo(Object obj) {
    return switch (obj) {
        case String s -> "String: " + s;
        case Integer i -> "Integer: " + i;
        case null -> "Null value";
        default -> "Unknown type";
    };
}

优点: 密封类正式版本、更强的类型系统、长期支持版本


JDK 18 (2022年3月)

1. 简单Web服务器

# 启动简单HTTP服务器
jwebserver
# 或指定端口和目录
jwebserver -p 9000 -d /path/to/directory

2. UTF-8默认字符集

// 现在默认使用UTF-8编码
FileReader reader = new FileReader("file.txt"); // UTF-8

优点: 内置Web服务器方便开发、字符编码统一


JDK 19 (2022年9月)

1. Virtual Threads (预览)

// 传统线程
Thread thread = new Thread(() -> {
    System.out.println("Hello from thread");
});
thread.start();

// Virtual Thread
Thread virtualThread = Thread.ofVirtual().start(() -> {
    System.out.println("Hello from virtual thread");
});

// 批量创建虚拟线程
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    for (int i = 0; i < 10000; i++) {
        executor.submit(() -> {
            // 处理任务
            System.out.println("Task executed");
        });
    }
}

2. Pattern Matching for switch (预览)

public void processObject(Object obj) {
    switch (obj) {
        case String s when s.length() > 5 -> 
            System.out.println("Long string: " + s);
        case Integer i when i > 0 -> 
            System.out.println("Positive integer: " + i);
        case null -> System.out.println("Null value");
        default -> System.out.println("Other type");
    }
}

优点: 虚拟线程大幅提升并发性能、模式匹配功能增强


JDK 20 (2023年3月)

1. Scoped Values (孵化)

public class ScopedValueExample {
    private static final ScopedValue<String> USER_ID = ScopedValue.newInstance();
    
    public void processRequest(String userId) {
        ScopedValue.where(USER_ID, userId)
            .run(() -> {
                // 在这个作用域内可以访问userId
                doSomething();
            });
    }
    
    private void doSomething() {
        String currentUser = USER_ID.get();
        System.out.println("Processing for user: " + currentUser);
    }
}

2. Vector API (孵化)

// SIMD运算支持
var a = IntVector.fromArray(species, array1, 0);
var b = IntVector.fromArray(species, array2, 0);
var c = a.add(b);
c.intoArray(result, 0);

优点: 作用域值提供线程安全的数据传递、向量化运算提升性能


JDK 21 (2023年9月) – LTS版本 🌟

1. Virtual Threads (正式)

// 创建虚拟线程
Thread.startVirtualThread(() -> {
    System.out.println("Running in virtual thread");
});

// 虚拟线程工厂
ThreadFactory factory = Thread.ofVirtual().factory();
Thread vThread = factory.newThread(() -> {
    // 任务代码
});

// 结构化并发
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
    Future<String> task1 = scope.fork(() -> fetchData1());
    Future<String> task2 = scope.fork(() -> fetchData2());
    
    scope.join();           // 等待所有任务完成
    scope.throwIfFailed();  // 如果有失败则抛出异常
    
    String result1 = task1.resultNow();
    String result2 = task2.resultNow();
}

2. Pattern Matching for switch (正式)

public String processValue(Object value) {
    return switch (value) {
        case null -> "null value";
        case String s when s.isEmpty() -> "empty string";
        case String s -> "string: " + s;
        case Integer i when i > 0 -> "positive integer: " + i;
        case Integer i -> "non-positive integer: " + i;
        case List<?> list when list.isEmpty() -> "empty list";
        case List<?> list -> "list with " + list.size() + " elements";
        default -> "unknown type: " + value.getClass().getSimpleName();
    };
}

3. Record Patterns (预览)

public record Point(int x, int y) {}
public record Rectangle(Point topLeft, Point bottomRight) {}

public void processRectangle(Object obj) {
    switch (obj) {
        case Rectangle(Point(var x1, var y1), Point(var x2, var y2)) -> {
            System.out.printf("Rectangle from (%d,%d) to (%d,%d)%n", 
                            x1, y1, x2, y2);
        }
        case Point(var x, var y) -> {
            System.out.printf("Point at (%d,%d)%n", x, y);
        }
        default -> System.out.println("Not a geometric shape");
    }
}

4. String Templates (预览)

String name = "World";
int value = 42;

// 字符串模板
String message = STR."Hello, \{name}! Value is \{value}";
// 结果: "Hello, World! Value is 42"

// 带格式化的模板
String formatted = FMT."Value: %d\{value}, Name: %s\{name}";

优点: 虚拟线程正式版本、模式匹配功能完善、记录模式简化数据提取


JDK 22 (2024年3月)

1. Unnamed Variables & Patterns

// 未命名变量
switch (value) {
    case Point(var x, var _) -> processX(x); // 忽略y坐标
    case Rectangle(var _, var bottomRight) -> processBottomRight(bottomRight);
}

// 在循环中忽略变量
for (var _ : collection) {
    doSomething(); // 不需要使用循环变量
}

2. String Templates (第二次预览)

// 自定义模板处理器
static final StringTemplate.Processor<String> UPPER = 
    StringTemplate.Processor.of((StringTemplate st) -> 
        st.interpolate().toUpperCase());

String result = UPPER."Hello \{name}!"; // "HELLO WORLD!"

3. Foreign Function & Memory API (预览)

// 调用本地函数
try (Arena arena = Arena.ofConfined()) {
    Linker linker = Linker.nativeLinker();
    SymbolLookup stdlib = linker.defaultLookup();
    
    MethodHandle strlen = linker.downcallHandle(
        stdlib.find("strlen").orElseThrow(),
        FunctionDescriptor.of(ValueLayout.JAVA_LONG, ValueLayout.ADDRESS)
    );
    
    MemorySegment cString = arena.allocateUtf8String("Hello, World!");
    long length = (long) strlen.invokeExact(cString);
    System.out.println("String length: " + length);
}

优点: 代码更简洁、字符串模板增强、本地互操作性提升


JDK 23 (2024年9月)

1. Primitive Types in Patterns (预览)

public void processNumber(Object obj) {
    switch (obj) {
        case int i when i > 0 -> System.out.println("Positive int: " + i);
        case int i when i < 0 -> System.out.println("Negative int: " + i);
        case int i -> System.out.println("Zero");
        case double d -> System.out.println("Double: " + d);
        default -> System.out.println("Not a number");
    }
}

2. Module Import Declarations (预览)

// 导入整个模块
import module java.base;

// 现在可以直接使用模块中的类型
String text = "Hello";
List<String> list = List.of("a", "b", "c");

3. Markdown Documentation Comments

/**
 * ## User Class
 * 
 * This class represents a user with the following properties:
 * 
 * - **Name**: The user's full name
 * - **Email**: The user's email address
 * - **Age**: The user's age in years
 * 
 * ### Example Usage
 * 
 * ```java
 * User user = new User("John Doe", "john@example.com", 30);
 * ```
 */
public class User {
    // ...
}

优点: 原始类型模式匹配、模块导入简化、文档支持Markdown


JDK 24 (2025年3月) – 预期特性

1. Value Objects (项目Valhalla)

// 值对象定义
value class Point {
    int x;
    int y;
    
    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

// 性能优化 - 无装箱开销
List<Point> points = List.of(
    new Point(1, 2),
    new Point(3, 4)
); // 直接存储值,无对象开销

2. Pattern Matching完整版本

// 完整的模式匹配支持
public void processData(Object data) {
    switch (data) {
        case User(var name, var email, var age) when age > 18 -> {
            System.out.println("Adult user: " + name);
        }
        case Product(var name, var price, var category) 
            when category.equals("electronics") && price > 1000 -> {
            System.out.println("Expensive electronic: " + name);
        }
        case List<String> list when !list.isEmpty() -> {
            System.out.println("String list with " + list.size() + " items");
        }
        default -> System.out.println("Unknown data type");
    }
}

3. Enhanced Collections

// 序列集合接口
SequencedCollection<String> seq = new ArrayList<>();
seq.addFirst("first");
seq.addLast("last");
String first = seq.getFirst();
String last = seq.getLast();

// 序列映射
SequencedMap<String, Integer> map = new LinkedHashMap<>();
map.putFirst("a", 1);
map.putLast("z", 26);

预期优点: 值对象大幅提升性能、模式匹配功能完善、集合API增强


🎯 重要版本总结

LTS (长期支持) 版本:

  • JDK 8: Lambda表达式、Stream API
  • JDK 11: HTTP客户端、字符串增强
  • JDK 17: 密封类、模式匹配
  • JDK 21: 虚拟线程、结构化并发

性能提升重点:

  • JDK 19-21: 虚拟线程革命性提升并发性能
  • JDK 24: 值对象减少内存开销
  • 各版本GC优化持续改进

开发体验改进:

  • JDK 8: 函数式编程
  • JDK 14-16: Records减少样板代码
  • JDK 17-23: 模式匹配简化代码逻辑
  • JDK 22-23: 字符串模板提升可读性

选择版本建议:

  • 生产环境: JDK 21 (最新LTS)
  • 新项目: JDK 21+ (享受最新特性)
  • 维护项目: 考虑从JDK 8/11升级到JDK 21

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注