Java 8(JDK1.8)核心新特性 Java 8JDK 1.8是 Java 历史上最重要的版本之一引入了函数式编程范式和大量现代语法特性。以下是核心新特性详解一、Lambda 表达式最重大的语法变革允许将函数作为参数传递。// 传统匿名内部类 Runnable r new Runnable() { Override public void run() { System.out.println(Hello); } }; // Lambda 表达式 Runnable r () - System.out.println(Hello); // 带参数示例 ListInteger nums Arrays.asList(1, 2, 3); nums.forEach(n - System.out.println(n)); // 方法引用更简洁 nums.forEach(System.out::println);二、函数式接口Functional Interface只包含一个抽象方法的接口可用FunctionalInterface注解标识。FunctionalInterface interface Calculator { int calculate(int a, int b); } // 使用 Calculator add (a, b) - a b; Calculator multiply (a, b) - a * b;核心内置函数式接口java.util.function包接口方法签名用途PredicateTboolean test(T t)断言/过滤FunctionT,RR apply(T t)类型转换ConsumerTvoid accept(T t)消费数据SupplierTT get()生成数据UnaryOperatorTT apply(T t)一元操作BinaryOperatorTT apply(T t1, T t2)二元操作三、Stream API对集合进行声明式、函数式操作支持链式调用和并行处理。ListInteger numbers Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // 过滤偶数平方排序求和 int sum numbers.stream() .filter(n - n % 2 0) // 过滤2,4,6,8,10 .map(n - n * n) // 映射4,16,36,64,100 .sorted() // 排序 .reduce(0, Integer::sum); // 归约220 // 并行流大数据量时使用 long count numbers.parallelStream() .filter(n - n 5) .count(); // 收集到集合 ListString result numbers.stream() .map(String::valueOf) .collect(Collectors.toList()); // 分组 MapString, ListInteger groups numbers.stream() .collect(Collectors.groupingBy(n - n 5 ? 大 : 小));Stream 操作分类中间操作filter,map,sorted,distinct,limit惰性求值终止操作forEach,collect,reduce,count触发执行四、接口默认方法与静态方法解决接口的扩展问题不破坏已有实现类。interface Animal { void eat(); // 抽象方法 // 默认方法实现类可选择性重写 default void sleep() { System.out.println(Sleeping...); } // 静态方法属于接口不继承 static void info() { System.out.println(This is an animal interface); } } class Dog implements Animal { Override public void eat() { System.out.println(Dog eating); } // 可选重写默认方法 Override public void sleep() { System.out.println(Dog sleeping); } }五、方法引用Method ReferenceLambda 的简写形式当 Lambda 体只有单一方法调用时使用。// 四种形式 list.forEach(System.out::println); // 对象::实例方法 list.sort(String::compareToIgnoreCase); // 类::实例方法 Stream.of(1,2,3).map(String::valueOf); // 类::静态方法 SupplierListString sup ArrayList::new; // 类::new构造器引用六、Optional 类优雅处理可能为null的值避免空指针异常。// 创建 OptionalString opt1 Optional.of(value); // 不能为null OptionalString opt2 Optional.ofNullable(null); // 可以为null OptionalString opt3 Optional.empty(); // 空对象 // 使用 String result opt2.orElse(default); // 为空则返回默认值 String result2 opt2.orElseGet(() - getDefault()); // 为空时惰性计算 String result3 opt2.orElseThrow(() - new RuntimeException(为空)); // 链式操作 opt2.filter(s - s.length() 3) .map(String::toUpperCase) .ifPresent(System.out::println); // 值存在时才执行七、新的日期时间 APIjava.time替代旧的Date/Calendar线程安全、不可变、设计清晰。// 当前日期时间 LocalDate date LocalDate.now(); // 2026-06-11 LocalTime time LocalTime.now(); // 15:11:30 LocalDateTime dateTime LocalDateTime.now(); // 构造指定时间 LocalDate birth LocalDate.of(2000, 1, 1); // 格式化与解析 DateTimeFormatter formatter DateTimeFormatter.ofPattern(yyyy-MM-dd HH:mm); String str dateTime.format(formatter); LocalDateTime parsed LocalDateTime.parse(2026-06-11 15:11, formatter); // 时区处理 ZonedDateTime zdt ZonedDateTime.now(ZoneId.of(Asia/Shanghai)); // 时间计算 LocalDate nextWeek date.plusWeeks(1); Period period Period.between(birth, date); // 计算日期间隔 Duration duration Duration.between(start, end); // 计算时间间隔 // 时间戳转换 Instant instant Instant.now(); // 类似 System.currentTimeMillis() long millis instant.toEpochMilli();八、Base64 编码内置 Base64 编解码无需第三方库如 Apache Commons Codec。// 编码 String encoded Base64.getEncoder().encodeToString(hello.getBytes()); // 解码 byte[] decoded Base64.getDecoder().decode(encoded); // URL 安全的 Base64替换 / 为 -_ String urlSafe Base64.getUrlEncoder().encodeToString(data); // MIME 格式每 76 字符换行 String mime Base64.getMimeEncoder().encodeToString(longData);九、并行数组操作Parallel Array Sortingint[] arr {3, 1, 4, 1, 5, 9, 2, 6}; // 并行排序大数据量时比 Arrays.sort 更快 Arrays.parallelSort(arr); // 并行前缀计算 Arrays.parallelPrefix(arr, (a, b) - a b); // 累加数组十、类型注解与重复注解// 重复注解 Repeatable(Schedules.class) interface Schedule { String day(); } Schedule(day Mon) Schedule(day Wed) class MyClass {} // 类型注解可用于泛型、类型转换等 ListNonNull String list;十一、其他重要特性特性说明Nashorn JavaScript 引擎在 JVM 上运行 JavaScriptJDK 11 已移除Metaspace替代 PermGen 永久代使用本地内存动态调整大小StampedLock比ReadWriteLock更高效的锁机制CompletableFuture强大的异步编程支持LongAdder/LongAccumulator高并发下比AtomicLong性能更好的原子类StringJoiner字符串拼接工具十二、CompletableFuture 异步编程示例CompletableFuture.supplyAsync(() - fetchData()) .thenApply(data - process(data)) .thenAccept(result - save(result)) .exceptionally(ex - { log.error(Error, ex); return null; });总结对比特性解决的问题Lambda Stream代码冗长、命令式编程繁琐Optional空指针异常、null 判断混乱新日期 API旧 API 设计差、线程不安全默认方法接口扩展不兼容方法引用Lambda 代码进一步简化