🌟 JDK8 新特性全解析
Java 8 是 Java 发展史上最重要的版本之一,它为 Java 引入了函数式编程、Stream API、全新的时间日期库等一系列现代化特性,极大地提升了开发效率与代码简洁性。
✨ 一览:JDK8 新特性速查表
特性名称 | 简要说明 |
---|---|
Lambda 表达式 | 支持函数式编程的核心语法 |
函数式接口 | 用 @FunctionalInterface 注解的单抽象方法接口 |
方法/构造器引用 | 简化 Lambda 表达式写法 |
Stream API | 操作集合的新方式,支持链式、并行、声明式处理 |
接口默认方法 | 接口可带有默认实现 |
Optional 类 | 用于优雅地处理空指针问题 |
新时间日期 API | 替代 Date/Calendar,提供强类型时间处理 |
重复注解 | 支持同一注解多次标注 |
类型注解 | 支持在泛型、参数等处添加注解 |
Nashorn 引擎 | Java 内嵌 JavaScript 脚本引擎 |
🔹 1. Lambda 表达式
Lambda 表达式是 Java 引入函数式编程的核心语法:
(参数) -> { 方法体 }
示例:
List<String> list = Arrays.asList("a", "b", "c");
list.forEach(item -> System.out.println(item));
🔹 2. 函数式接口(@FunctionalInterface)
函数式接口只包含一个抽象方法,适用于 Lambda 表达式。
@FunctionalInterface
public interface MyFunc {int doSomething(int x);
}
Java 提供了大量内置函数式接口,如:
-
Predicate<T>
:断言型函数 -
Function<T, R>
:函数型接口 -
Consumer<T>
:消费型接口 -
Supplier<T>
:供给型接口
🔹 3. 方法引用与构造器引用
用于简化 Lambda 表达式:
list.forEach(System.out::println); // 方法引用
Supplier<List<String>> s = ArrayList::new; // 构造器引用
🔹 4. Stream API(集合操作流式处理)
Stream API 是 Java 8 的重头戏之一,提供声明式的方式处理集合数据:
List<String> names = Arrays.asList("Tom", "Jerry", "Tony");List<String> result = names.stream().filter(name -> name.startsWith("T")).map(String::toUpperCase).collect(Collectors.toList());
Stream 支持:
-
中间操作:
filter
,map
,sorted
,limit
-
终结操作:
collect
,forEach
,count
,reduce
-
并行处理:
parallelStream()
🔹 5. 接口的默认方法与静态方法
Java 8 允许接口中带有具体实现方法:
interface MyInterface {default void hello() {System.out.println("Hello from interface");}static void staticMethod() {System.out.println("Static method in interface");}
}
🔹 6. Optional 类(优雅处理 null)
Optional 是 Java 8 新增的容器类,用于解决 null 值处理问题:
Optional<String> name = Optional.ofNullable(getName());name.ifPresent(System.out::println);String defaultName = name.orElse("默认值");
常用方法:
-
of()
,ofNullable()
,isPresent()
-
orElse()
,orElseGet()
,orElseThrow()
-
map()
,flatMap()
,filter()
🔹 7. 新的时间日期 API(java.time)
替代 Date
和 Calendar
,提供更现代的时间操作:
LocalDate today = LocalDate.now();
LocalDate birth = LocalDate.of(2000, 1, 1);
Period age = Period.between(birth, today);System.out.println("年龄:" + age.getYears());
常用类:
-
LocalDate
,LocalTime
,LocalDateTime
-
Period
,Duration
-
DateTimeFormatter
(格式化) -
ZoneId
,ZonedDateTime
(时区)
🔹 8. 重复注解(@Repeatable)
允许同一注解在同一位置使用多次:
@Schedule(day = "Monday")
@Schedule(day = "Tuesday")
public class MyTask {}
🔹 9. 类型注解
Java 8 增强了注解的使用范围,可以用在泛型参数、类型上等位置:
Map<@NonNull String, @Nullable String> userMap;
🔹 10. Nashorn JavaScript 引擎
Java 8 引入 Nashorn,可直接在 Java 中运行 JS 代码:
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.eval("print('Hello from JS')");
⚠️ 注意:Nashorn 在 Java 15 开始被移除。