xmlns="http://www.w3.org/2000/svg"style="display:是一个里程碑式的版本,引入了许多革命性的新特性,极大地改变了Java编程的方式。以下是JavaExpressions)核心特性:函数式编程的基础,简化匿名内部类的写法//Java匿名内部类Runnabler1=newRunnable(){@Overridepublicvoidrun(){System.out.println("HelloWorld");}};//JavaLambda表达式Runnabler2=()->System.out.println("HelloWorld");//更多示例Comparator<String>comparator=(s1,s2)->s1.compareTo(s2);Consumer<String>consumer=s->System.out.println(s);Function<Integer,String>function=i->"Number:"+i;2.Interfaces)定义:只有一个抽象方法的接口,可以使用@FunctionalInterface注解标识@FunctionalInterfaceinterfaceMyFunctionalInterface{voidexecute();//可以有默认方法defaultvoiddefaultMethod(){System.out.println("默认方法");}//可以有静态方法staticvoidstaticMethod(){System.out.println("静态方法");}}//内置函数式接口Consumer<T>//消费型接口:接受一个参数,无返回值Supplier<T>//供给型接口:无参数,返回一个值Function<T,R>//函数型接口:接受T类型参数,返回R类型结果Predicate<T>//断言型接口:接受T类型参数,返回boolean3.StreamAPI核心特性:对集合数据进行函数式操作,支持并行处理List<String>list=Arrays.asList("apple","banana","orange","grape");//传统方式传统:筛选长度>5的水果并排序List<String>result1=newArrayList<>();for(Stringfruit:list){if(fruit.length()>5){result1.add(fruit);}}Collections.sort(result1);//Stream方式List<String>result2=list.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);//并行流处理longcount=list.parallelStream()//并行流.filter(s->s.length()>5).count();4.方法引用(MethodReferences)核心特性:进一步简化Lambda表达式//静态方法引用Function<String,Integer>parser=Integer::parseInt;//实例方法引用Consumer<String>printer=System.out::println;//特定对象的实例方法引用Stringstr="Hello";Supplier<Integer>lengthSupplier=str::length;//构造器引用Supplier<List<String>>listSupplier=ArrayList::new;Function<Integer,String[]>arrayCreator=String[]::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){Addressaddress=user.getAddress();if(address!=null){returnaddress.getCity();}}return"Unknown";}//Optional方式更优雅publicStringgetCity(Useruser){returnOptional.ofNullable(user).map(User::getAddress).map(Address::getCity).orElse("Unknown");}//Optional使用示例Optional<String>optional=Optional.of("Hello");optional.ifPresent(System.out::println);//输出:HelloOptional<String>empty=Optional.empty();Stringresult=empty.orElse("Default");//返回:"Default"Optional<String>nullable=Optional.ofNullable(null);Stringvalue=nullable.orElseGet(()->"Generated");//新的日期时间API(java.time包)核心特性:不可变、线程安全的日期时间处理//旧API的问题:可变、线程不安全DateoldDate=newDate();Calendarcalendar=Calendar.getInstance();//新日期时间APILocalDatedate=LocalDate.now();//当前日期:2026-02-17LocalTimetime=LocalTime.now();//当前时间:11:22:34LocalDateTimedateTime=LocalDateTime.now();//创建特定日期LocalDatebirthday=LocalDate.of(1990,5,15);LocalDateTimemeeting=LocalDateTime.of(2026,2,20,14,30);//日期运算LocalDatenextWeek=date.plusWeeks(1);LocalDatelastMonth=date.minusMonths(1);//日期比较booleanisAfter=date.isAfter(birthday);Periodperiod=Period.between(birthday,date);//格式化DateTimeFormatterformatter=DateTimeFormatter.ofPattern("yyyy-MM-ddHH:mm:ss");Stringformatted=dateTime.format(formatter);//时区处理ZonedDateTimezoned=ZonedDateTime.now(ZoneId.of("Asia/Shanghai"));8.NashornJavaScript引擎核心特性:替代Rhino的轻量级高性能JavaScript引擎ScriptEngineengine=newScriptEngineManager().getEngineByName("nashorn");engine.eval("print('HellofromJavaScript')");//在Java中调用JavaScript函数engine.eval("functionadd(a,}");Invocableinvocable=(Invocable)engine;Objectresult=invocable.invokeFunction("add",5,3);System.out.println(result);//输出:89.Annotations)核心特性:同一个注解可以在同一位置多次使用//定义可重复注解@Repeatable(Schedules.class)@interfaceSchedule{StringdayOfMonth()default"first";StringdayOfWeek()default"Mon";}@interfaceSchedules{Schedule[]value();}//使用重复注解@Schedule(dayOfMonth="last")@Schedule(dayOfWeek="Fri")classPeriodicTask{//...}10.类型注解和参数名反射核心特性:注解可以用于更多地方,支持获取方法参数名//类型注解注解可以用于任何类型使用的地方@NotNullStringname=getUserName();List<@EmailString>emails=getEmails();//参数名反射(需要编译时加上参数)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支持,无需第三方库Stringoriginal="HelloJava8";Stringencoded=Base64.getEncoder().encodeToString(original.getBytes());Stringdecoded=newString(Base64.getDecoder().decode(encoded));//URL安全的Base64StringurlSafe=Base64.getUrlEncoder().encodeToString(original.getBytes());实际应用示例函数式数据处理List<Person>people=Arrays.asList(newPerson("Alice",25),newPerson("Bob",30),newPerson("Charlie",35));//筛选年龄>28的人,提取姓名,排序,收集为列表List<String>names=people.stream().filter(p->p.getAge()>28).map(Person::getName).sorted().collect(Collectors.toList());//按年龄分组Map<Integer,List<Person>>byAge=people.stream().collect(Collectors.groupingBy(Person::getAge));//计算平均年龄doubleaverageAge=people.stream().mapToInt(Person::getAge).average().orElse(0.0);总结Java8的新特性彻底改变了Java编程范式:函数式编程:Lambda表达式、StreamAPI接口增强:默认方法、静态方法更好的API设计:Optional、新的日期时间API性能提升:并行流、并行排序这些特性使得Java代码更加简洁、可读性更强,并且更好地利用了多核处理器的能力,为现代Java开发奠定了基础。