Java8 有哪些新特性?

📅 发布时间:2026/7/5 20:52:41 👁️ 浏览次数:
Java8 有哪些新特性?
Java 8 是一个里程碑式的版本引入了许多革命性的新特性极大地改变了Java编程的方式。以下是Java 8的主要新特性1. Lambda表达式Lambda Expressions核心特性函数式编程的基础简化匿名内部类的写法// Java 7 - 匿名内部类Runnabler1newRunnable(){Overridepublicvoidrun(){System.out.println(Hello World);}};// Java 8 - Lambda表达式Runnabler2()-System.out.println(Hello World);// 更多示例ComparatorStringcomparator(s1,s2)-s1.compareTo(s2);ConsumerStringconsumers-System.out.println(s);FunctionInteger,Stringfunctioni-Number: i;2. 函数式接口Functional Interfaces定义只有一个抽象方法的接口可以使用FunctionalInterface注解标识FunctionalInterfaceinterfaceMyFunctionalInterface{voidexecute();// 可以有默认方法defaultvoiddefaultMethod(){System.out.println(默认方法);}// 可以有静态方法staticvoidstaticMethod(){System.out.println(静态方法);}}// 内置函数式接口ConsumerT// 消费型接口接受一个参数无返回值SupplierT// 供给型接口无参数返回一个值FunctionT,R// 函数型接口接受T类型参数返回R类型结果PredicateT// 断言型接口接受T类型参数返回boolean3. Stream API核心特性对集合数据进行函数式操作支持并行处理ListStringlistArrays.asList(apple,banana,orange,grape);// 传统方式 vs Stream方式// 传统筛选长度5的水果并排序ListStringresult1newArrayList();for(Stringfruit:list){if(fruit.length()5){result1.add(fruit);}}Collections.sort(result1);// Stream方式ListStringresult2list.stream().filter(fruit-fruit.length()5).sorted().collect(Collectors.toList());// Stream操作示例list.stream().filter(s-s.startsWith(a))// 中间操作过滤.map(String::toUpperCase)// 中间操作映射.forEach(System.out::println);// 终止操作遍历// 并行流处理longcountlist.parallelStream()// 并行流.filter(s-s.length()5).count();4. 方法引用Method References核心特性进一步简化Lambda表达式// 四种方法引用形式// 1. 静态方法引用FunctionString,IntegerparserInteger::parseInt;// 2. 实例方法引用ConsumerStringprinterSystem.out::println;// 3. 特定对象的实例方法引用StringstrHello;SupplierIntegerlengthSupplierstr::length;// 4. 构造器引用SupplierListStringlistSupplierArrayList::new;FunctionInteger,String[]arrayCreatorString[]::new;5. 接口的默认方法和静态方法核心特性接口可以包含具体实现的方法interfaceVehicle{// 传统抽象方法voidstart();// 默认方法 - 有具体实现defaultvoidhonk(){System.out.println(车辆鸣笛);}// 静态方法 - 接口级别的工具方法staticintgetWheelCount(){return4;}}interfaceAlarm{defaultvoidhonk(){System.out.println(警报鸣响);}}classCarimplementsVehicle,Alarm{Overridepublicvoidstart(){System.out.println(汽车启动);}// 解决默认方法冲突Overridepublicvoidhonk(){Vehicle.super.honk();// 明确调用Vehicle的默认方法Alarm.super.honk();// 明确调用Alarm的默认方法}}6. Optional类核心特性优雅地处理null值避免NullPointerException// 传统方式 - 繁琐的null检查publicStringgetCity(Useruser){if(user!null){Addressaddressuser.getAddress();if(address!null){returnaddress.getCity();}}returnUnknown;}// Optional方式 - 更优雅publicStringgetCity(Useruser){returnOptional.ofNullable(user).map(User::getAddress).map(Address::getCity).orElse(Unknown);}// Optional使用示例OptionalStringoptionalOptional.of(Hello);optional.ifPresent(System.out::println);// 输出HelloOptionalStringemptyOptional.empty();Stringresultempty.orElse(Default);// 返回DefaultOptionalStringnullableOptional.ofNullable(null);Stringvaluenullable.orElseGet(()-Generated);// 惰性求值7. 新的日期时间APIjava.time包核心特性不可变、线程安全的日期时间处理// 旧API的问题可变、线程不安全DateoldDatenewDate();CalendarcalendarCalendar.getInstance();// 新日期时间APILocalDatedateLocalDate.now();// 当前日期2026-02-17LocalTimetimeLocalTime.now();// 当前时间11:22:34LocalDateTimedateTimeLocalDateTime.now();// 当前日期时间// 创建特定日期LocalDatebirthdayLocalDate.of(1990,5,15);LocalDateTimemeetingLocalDateTime.of(2026,2,20,14,30);// 日期运算LocalDatenextWeekdate.plusWeeks(1);LocalDatelastMonthdate.minusMonths(1);// 日期比较booleanisAfterdate.isAfter(birthday);PeriodperiodPeriod.between(birthday,date);// 格式化DateTimeFormatterformatterDateTimeFormatter.ofPattern(yyyy-MM-dd HH:mm:ss);StringformatteddateTime.format(formatter);// 时区处理ZonedDateTimezonedZonedDateTime.now(ZoneId.of(Asia/Shanghai));8. Nashorn JavaScript引擎核心特性替代Rhino的轻量级高性能JavaScript引擎ScriptEngineenginenewScriptEngineManager().getEngineByName(nashorn);engine.eval(print(Hello from JavaScript));// 在Java中调用JavaScript函数engine.eval(function add(a, b) { return a b; });Invocableinvocable(Invocable)engine;Objectresultinvocable.invokeFunction(add,5,3);System.out.println(result);// 输出89. 重复注解Repeating Annotations核心特性同一个注解可以在同一位置多次使用// 定义可重复注解Repeatable(Schedules.class)interfaceSchedule{StringdayOfMonth()defaultfirst;StringdayOfWeek()defaultMon;}interfaceSchedules{Schedule[]value();}// 使用重复注解Schedule(dayOfMonthlast)Schedule(dayOfWeekFri)classPeriodicTask{// ...}10. 类型注解和参数名反射核心特性注解可以用于更多地方支持获取方法参数名// 类型注解 - 注解可以用于任何类型使用的地方NotNullStringnamegetUserName();ListEmailStringemailsgetEmails();// 参数名反射需要编译时加上 -parameters 参数publicvoidprocess(Param(id)intid,Param(name)Stringname){// 可以通过反射获取参数名}11. 并行数组排序核心特性Arrays.parallelSort()提供更好的多核性能int[]numbers{5,2,8,1,9,3};// 传统排序Arrays.sort(numbers);// 并行排序 - 大数据量时性能更好Arrays.parallelSort(numbers);12. Base64编码解码核心特性内置Base64支持无需第三方库StringoriginalHello Java 8;StringencodedBase64.getEncoder().encodeToString(original.getBytes());StringdecodednewString(Base64.getDecoder().decode(encoded));// URL安全的Base64StringurlSafeBase64.getUrlEncoder().encodeToString(original.getBytes());实际应用示例函数式数据处理ListPersonpeopleArrays.asList(newPerson(Alice,25),newPerson(Bob,30),newPerson(Charlie,35));// 筛选年龄28的人提取姓名排序收集为列表ListStringnamespeople.stream().filter(p-p.getAge()28).map(Person::getName).sorted().collect(Collectors.toList());// 按年龄分组MapInteger,ListPersonbyAgepeople.stream().collect(Collectors.groupingBy(Person::getAge));// 计算平均年龄doubleaverageAgepeople.stream().mapToInt(Person::getAge).average().orElse(0.0);总结Java 8的新特性彻底改变了Java编程范式函数式编程Lambda表达式、Stream API接口增强默认方法、静态方法更好的API设计Optional、新的日期时间API性能提升并行流、并行排序这些特性使得Java代码更加简洁、可读性更强并且更好地利用了多核处理器的能力为现代Java开发奠定了基础。