Java 8新特性概览:主要更新与功能详解
Java 8 是 Java 语言发展史上的一个重要里程碑,引入了许多革命性的新特性。以下是 Java 8 的主要新特性:
1. Lambda 表达式 (函数式编程)
Lambda 表达式是 Java 8 最显著的特性,它使代码更简洁,并支持函数式编程风格。
// 旧方式 - 匿名内部类
Runnable r1 = new Runnable() {
@Override
public void run() {
System.out.println("Hello World");
}
};
// Java 8 - Lambda 表达式
Runnable r2 = () -> System.out.println("Hello World");
2. 函数式接口 (Functional Interfaces)
函数式接口是只包含一个抽象方法的接口,可以使用 @FunctionalInterface 注解标记。
@FunctionalInterface
interface MyFunctionalInterface {
void execute();
// 可以有默认方法
default void defaultMethod() {
System.out.println("Default method");
}
// 可以有静态方法
static void staticMethod() {
System.out.println("Static method");
}
}
3. 方法引用 (Method References)
方法引用是 Lambda 表达式的简写形式,用于直接引用已有方法。
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
// Lambda 表达式
names.forEach(s -> System.out.println(s));
// 方法引用
names.forEach(System.out::println);
4. Stream API
Stream API 提供了一种高效处理集合数据的新方式,支持链式操作和并行处理。
List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
// 过滤空字符串并统计数量
long count = strings.stream()
.filter(string -> !string.isEmpty())
.count();
// 并行处理
long parallelCount = strings.parallelStream()
.filter(string -> !string.isEmpty())
.count();
5. 默认方法 (Default Methods)
允许在接口中定义具有实现的方法,使用 default 关键字。
interface Vehicle {
default void print() {
System.out.println("我是一辆车!");
}
static void blowHorn() {
System.out.println("按喇叭!!!");
}
}
6. Optional 类
用于避免 NullPointerException,优雅地处理可能为 null 的值。
Optional<String> optional = Optional.of("Java8");
// 检查值是否存在
if (optional.isPresent()) {
System.out.println(optional.get());
}
// 如果值存在则执行操作
optional.ifPresent(System.out::println);
// 如果值不存在则返回默认值
String nullValue = null;
Optional<String> opt = Optional.ofNullable(nullValue);
String result = opt.orElse("默认值");
7. 新的日期时间 API (java.time)
全新的日期时间 API 解决了旧 java.util.Date 和 java.util.Calendar 的问题。
// 当前日期
LocalDate today = LocalDate.now();
System.out.println("当前日期: " + today);
// 当前时间
LocalTime time = LocalTime.now();
System.out.println("当前时间: " + time);
// 当前日期和时间
LocalDateTime now = LocalDateTime.now();
System.out.println("当前日期和时间: " + now);
// 日期计算
LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS);
System.out.println("一周后的日期: " + nextWeek);
8. Nashorn JavaScript 引擎
Java 8 引入了新的 JavaScript 引擎 Nashorn,替代了旧的 Rhino 引擎。
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("nashorn");
// 执行 JavaScript 代码
try {
engine.eval("print('Hello Nashorn!')");
} catch (ScriptException e) {
e.printStackTrace();
}
9. Base64 支持
Java 8 内置了 Base64 编码解码器。
// 编码
String original = "Java8 Base64 编码解码";
String encoded = Base64.getEncoder().encodeToString(original.getBytes());
System.out.println("编码后: " + encoded);
// 解码
byte[] decodedBytes = Base64.getDecoder().decode(encoded);
String decoded = new String(decodedBytes);
System.out.println("解码后: " + decoded);
10. 并行数组排序
Arrays 类新增了并行排序方法。
int[] numbers = {5, 3, 9, 1, 7, 2, 8, 4, 6};
// 并行排序
Arrays.parallelSort(numbers);
System.out.println(Arrays.toString(numbers));
11. 类型注解和重复注解
Java 8 扩展了注解的应用范围,并支持重复注解。
// 类型注解
@NonNull String str = "Hello";
// 重复注解
@Role("admin")
@Role("user")
public class User {
// ...
}
// 定义可重复注解
@Repeatable(Roles.class)
public @interface Role {
String value();
}
public @interface Roles {
Role[] value();
}
12. CompletableFuture 改进
增强了 CompletableFuture 类,支持更强大的异步编程。
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
return "结果";
});
future.thenAccept(System.out::println)
.thenRun(() -> System.out.println("完成"));
作者:梦幻南瓜