JDK版本语法和API的变化(8-15)

① Java 8

Lambda 表达式。

接口可以添加非抽象方法(默认实现的方法),default关键字。
函数式接口Functional Interface
内置的函数式接口:Predicate断言、Function、Supplier生产者、Consumer消费者、Comparator

新的日期和时间API,LocalDate、LocalDateTime、LocalTime、Timezones时区、Clock。

Optional 类优雅解决空指针异常。

Stream API 函数式编程:Filter过滤、Sorted排序、Map转换、Match匹配、Count计数、Reduce
Parallel Streams 并行流

Nashorn, JavaScript 引擎,在 JVM 上运行 JS。

JVM 移除永久代,增加 MetaSpace(元空间)。

https://openjdk.org/projects/jdk8/features

通过Lambda表达式遍历集合

map.forEach((k,v) -> {
	System.out.println("k=" + k + ",v=" + v);
});

list.forEach(v -> {
	System.out.println(v);
});

//或者通过双冒号遍历
list.forEach(System.out::println);

Lambda代替匿名内部类

Runnable r1 = new Runnable(){
	@Override
	public void run(){
		System.out.println("普通方式创建!");
	}	
};

//使用lambda创建
Runnable r2 = () -> System.out.println("lambda方式创建");

Stream

【所有的Stream的操作,必须以lambda表达式为参数】

//使用流进行过滤
List<String> result = list.stream().filter(str -> !"jordan".equals(str)).collect(Collectors.toList());
System.out.println(result);

构造Stream流的方式

Stream stream1 = Stream.of("a","b","c"); //1. 直接通过of方法

String[] strArray = new String[]{"a","b","c"};
stream2 = Stream.of(strArray); //通过对数组进行转化为stream

stream3 = Arrays.stream(strArray); //2. 数组——> Stream

List<String> list = Arrays.asList(strArray);
stream4 = list.stream();// 集合 ——> stream

Stream流之间的转换

try{
	Stream<String> stream = Stream.of("a","b","c");

	//转换成Array
	String[] strArray1 = stream.toArray(String[]::new);

	//转换成Collection
	List<String> list1 = stream.collect(Collectors.toList());
	List<String> list2 = stream.collect(Collectors.toCollection(ArrayList::new));
	Set set = stream.collect(Collectors.toSet());
	
	Stack stack = stream.collect(Collectors.toCollection(Stack::new));

	//转换成String
	String str = stream.collect(Collectors.joining()).toString();
	
}catch(Exception e){
	e.printStackTrace();
}

Stream流的map使用

map方法用于映射每个元素到对应的结果

/**
	转换大写
*/
List<String> list = Arrays.asList("jordan","kobe","james");
System.out.println("转换之前的数据:" + list);

List<String> list2 = list.stream().map(String::toUpperCase).collect(Collectors.toList());
System.out.println("转换之后的数据:" + list2);
/**
	转换数据类型
	String--->Integer
*/
List<String> list = Arrays.asList("1","2",""3);
System.out.println("转换之前的数据:" + list);

List<Integer> list2 = list.stream().map(Integer::valueOf).collect(Collectors.toList());
/**
	获取平方
*/
List<Integer> list = Arrays.asList(new Interger[]{1,2,3,4,5});
List<Integer> list2 = list.stream().map(n -> n * n).collect(Collectors.toList());

Stream流的filter使用

filter方法用于通过设置的条件过滤出元素

/**
	通过findAny得到if/else
*/
List<String> list = Arrays.asList("jordan","kobe","james","yaoming");
String result = list.stream().filter(str -> "jordan".equals(str)).findAny().orElse("找不到");
/**
	通过mapToInt计算和
*/
List<User> lists = new ArrayList<>();
lists.add(new User(6,"jordan"));
lists.add(new User(2,"kobe"));
lists.add(new User(3,"yuan"));
lists.add(new User(9,"yuan"));

//计算这个list中出现jordan id的值
int sum = lists.stream().filter(u -> "yuan".equals(u.getName())).mapToInt(u -> u.getId()).sum();]
System.out.println("计算结果:"+sum);

Stream流flatMap使用

flatMap方法用于映射每个元素到对应的结果,一对多

/**
	从句子中得到单词
*/
String words = "The way of the future";
List<String> list = new ArrayList<>();
list.add(words);

List<String> list2 = list.stream().flatMap(str -> Stream.of(str.split(" "))).filter(word -> word.length > 0).collect();
list2.forEach(System.out::println);

Stream流的limit使用

用于获取指定数量的流

//获取前三条数据
Random rd = new Random();
rd.ints().limit(3).forEach(System.out::println);
//结合skip得到所需要的数据,skip表示扔掉前n个元素
List<User> list = new ArrayList<>();
for(int i = 1;i < 4; i++){
	User user = new User(i,"pancm"+i);
	list.add(user);
}

//获取前三条数据,但需要扔掉前两条,结果:就剩下第三条数据
List<Stream> list2 = list.stream().map(User::getName).limit(3).skip(2).collect(Collectors.toList());

Stream流的sort使用

sorted方法对于流进行升序排序

//随机取值排序
Random rd = new Random();
rd.ints().limit(3).sorted().forEach(System.out::println);//取到前三条进行排序
//普通排序
List<User> list2 = list1.stream().sorted((u1, u2) -> u1.getName().compareTo(u2.getName())).limit(3).collect(Collectors.toList());

//优化排序(先获取,后排序)
List<User> list3 = list1.stream().limit(3).sorted((u1, u2) -> u1.getName().compareTo(u2.getName())).collect(Collectors.toList());

Stream流的peek使用

peek对每个元素执行操作并返回一个新的stream

Stream.of("one", "two", "three", "four").filter(e -> e.length() > 3).peek(e -> System.out.println("转换之前: " + e)).map(String::toUpperCase).peek(e -> System.out.println("转换之后: " + e)).collect(Collectors.toList());

Stream流的parallel使用

parallelStream 是流并行处理程序的代替方法。

/**
	获取空字符串的数量
*/
List<String> strings = Arrays.asList("a", "", "c", "", "e","", " ");
long count = strings.parallelStream().filter(string -> string.isEmpty()).count();

Stream流的max/min/distinct使用

/**
	得到最大最小值(字符串长度)
*/
List<String> list = Arrays.asList("jordan","kobe","james","yao");
int maxLines = list.stream().mapToInt(String::length).max().getAsInt();
int minLines = list.stream().mapToInt(String::length).min().getAsInt();
//去重
String lines = "good good study day day up";
List<String> list = new ArrayList<>();
list.add(lines);

List<String> words = list.stream().flatMap(line -> Stream.of(line.split(" "))).filter(word -> word.length() > 0).map(String::toLowerCase).distinct()
	.sorted().collect(Collectors.toList());

Stream流的Match使用

  • allMatch:Stream 中全部元素符合则返回 true
  • anyMatch:Stream 中只要有一个元素符合则返回 true;
  • noneMatch:Stream 中没有一个元素符合则返回 true
boolean all = lists.stream.allMatch(u -> u.getId() > 3);
System.out.println("是否都大于3:" + all);

 boolean any = lists.stream().anyMatch(u -> u.getId() > 3);
 System.out.println("是否有一个大于3:" + any);
 
 boolean none = lists.stream().noneMatch(u -> u.getId() > 3);
 System.out.println("是否没有一个大于3的:" + none);  

Stream流的reduce使用

reduce 主要作用是把 Stream 元素组合起来进行操作。

//字符串连接
String concat = Stream.of("A","B","C","D").reduce("",String::concat);
System.out.println("字符串拼接:" + concat);
//得到最小值
double minValue = Stream.of(-4.0, 1.0, 3.0, -2.0).reduce(Double.MAX_VALUE, Double::min);
System.out.println("最小值:" + minValue);
//求和,无起始值
int sumValue = Stream.of(1,2,3,4).reduce(Integer::sum).get();

//求和,有起始值
sumValue = Stream.of(1,2,3,4).reduce(1,Integer::sum);
//过滤拼接
concat = Stream.of("a", "B", "c", "D", "e", "F").filter(x -> x.compareTo("Z") > 0).reduce("", String::concat);

Stream流的iterate使用

【iterate 跟 reduce 操作很像,接受一个种子值,和一个UnaryOperator(例如 f)。然后种子值成为 Stream 的第一个元素,f(seed) 为第二个,f(f(seed)) 第三个,以此类推。在 iterate 时候管道必须有 limit 这样的操作来限制 Stream 大小】

//生成一个等差数列(从2开始)
System.iterate(2,n-> n+2).limit(5).forEach(x -> System.out.println(x + ""));

Stream流的 Supplier 使用

通过实现Supplier类的方法可以自定义流计算规则。

//自定义一个流计算规则
Stream.generate(new UserSupplier())
	.limit(2).forEach(u -> System.out.println(u.getId() + ", " + u.getName()));

class UserSupplier implements Supplier<User>{
	
	private int index = 10;
	private Random random = new Random();
	
	@Override
	public User get(){
		return new User(index++,"pancm" + random.nextInt(10));
	}
}

Stream流的groupingBy/partitioningBy使用

  • groupingBy:分组排序
  • partitioningBy:分区排序
//分组排序
Map<Integer,List<User>> personGroups = Stream.generate(new UserSupplier2()).limit(5)
	.collect(Collectors.groupingBy(User::getId));

Iterator it = personGroups.entrySet().iterator();
while(it.hasNext()){
	Map.Entry<Integer,List<User>> persons = (Map.Entry)it.next();
	System.out.println("id " + persons.getKey() + " = " + persons.getValue());
}


class UserSupplier2 implements Supplier<User> {
  private int index = 10;
  private Random random = new Random();
 
  @Override
  public User get() {
   return new User(index % 2 == 0 ? index++ : index, "pancm" + random.nextInt(10));
  }
 }
Map<Boolean, List<User>> children = Stream.generate(new UserSupplier3()).limit(5)
   .collect(Collectors.partitioningBy(p -> p.getId() < 18));

 System.out.println("小孩: " + children.get(true));
 System.out.println("成年人: " + children.get(false));

class UserSupplier3 implements Supplier<User> {
  private int index = 16;
  private Random random = new Random();
 
  @Override
  public User get() {
   return new User(index++, "pancm" + random.nextInt(10));
  }
 }

Stream流的summaryStatistics使用

用于收集统计信息(如count、min、max、sum和average)的状态对象

//得到最大、最小、之和以及平均数
List<Integer> numbers = Arrays.asList(1, 5, 7, 3, 9);
IntSummaryStatistics stats = numbers.stream().mapToInt((x) -> x).summaryStatistics();

System.out.println("列表中最大的数 : " + stats.getMax());
System.out.println("列表中最小的数 : " + stats.getMin());
System.out.println("所有数之和 : " + stats.getSum());
System.out.println("平均数 : " + stats.getAverage());

全新的日期时间

  • Instant:瞬时时间
  • LocalDate:本地日期,不包含具体时间,格式yyyy-MM-dd
  • LocalTime:本地时间,不包含日期,格式yyyy-MM-dd HH:mm:ss:SSS
  • LocalDateTime:组合了日期和时间,但不包含时差和时区信息
  • ZonedDateTime:最完整的日期时间,包含时区和相对UTC或格林威治的时差
/**
	获取当前的日期时间
*/
LocalDate nowDate = LocalDate.now();
LocalDateTime nowDateTime = LocalDateTime.now();

/**
	获取当前的年月日时分秒
*/
LocalDateTime ldt = LocalDateTime.now();
 System.out.println("当前年:"+ldt.getYear());   //2018
  System.out.println("当前年份天数:"+ldt.getDayOfYear());//172 
  System.out.println("当前月:"+ldt.getMonthValue());
  System.out.println("当前时:"+ldt.getHour());
  System.out.println("当前分:"+ldt.getMinute());
  System.out.println("当前时间:"+ldt.toString());
//格式化时间
LocalDateTime ldt = LocalDateTime.now();
System.out.println("格式化时间: "+ ldt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")));
//时间增减
LocalDateTime ldt = LocalDateTime.now();
System.out.println("后5天时间:"+ldt.plusDays(5));
System.out.println("前5天时间并格式化:"+ldt.minusDays(5).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))); //2018-06-16
System.out.println("前一个月的时间:"+ldt2.minusMonths(1).format(DateTimeFormatter.ofPattern("yyyyMM"))); //2018-06-16
System.out.println("后一个月的时间:"+ldt2.plusMonths(1)); //2018-06-16
System.out.println("指定2099年的当前时间:"+ldt.withYear(2099)); //2099-06-21T15:07:39.506
//创建指定时间
LocalDate ld3=LocalDate.of(2017, Month.NOVEMBER, 17);
LocalDate ld4=LocalDate.of(2018, 02, 11);
//时间相差比较
LocalDate ld=LocalDate.parse("2017-11-17");
LocalDate ld2=LocalDate.parse("2018-01-05");
Period p=Period.between(ld, ld2);
System.out.println("相差年: "+p.getYears()+" 相差月 :"+p.getMonths() +" 相差天:"+p.getDays());
// 相差年: 0 相差月 :1 相差天:19
//注:这里的月份是不满足一年,天数是不满足一个月的。这里实际相差的是1月19天,也就是49天。
//相差总数的时间
//注:ChronoUnit也可以计算相差时分秒。
  LocalDate startDate = LocalDate.of(2017, 11, 17);
        LocalDate endDate = LocalDate.of(2018, 01, 05);
        System.out.println("相差月份:"+ChronoUnit.MONTHS.between(startDate, endDate));
        System.out.println("两月之间的相差的天数   : " + ChronoUnit.DAYS.between(startDate, endDate));
  //        相差月份:1
  //        两天之间的差在天数   : 49
//精度时间相差  Duration 这个类以秒和纳秒为单位建模时间的数量或数量
Instant inst1 = Instant.now();
    System.out.println("当前时间戳 : " + inst1);
    Instant inst2 = inst1.plus(Duration.ofSeconds(10));
    System.out.println("增加之后的时间 : " + inst2);
    System.out.println("相差毫秒 : " + Duration.between(inst1, inst2).toMillis());
    System.out.println("相毫秒 : " + Duration.between(inst1, inst2).getSeconds());
 // 当前时间戳 : 2018-12-19T08:14:21.675Z
 // 增加之后的时间 : 2018-12-19T08:14:31.675Z
 // 相差毫秒 : 10000
 // 相毫秒 : 10

//时间大小比较
LocalDateTime ldt4 = LocalDateTime.now();
LocalDateTime ldt5 = ldt4.plusMinutes(10);
System.out.println("当前时间是否大于:"+ldt4.isAfter(ldt5));
System.out.println("当前时间是否小于"+ldt4.isBefore(ldt5));
// false
// true
//得到其他时区的时间
Clock clock = Clock.systemUTC();
System.out.println("当前时间戳 : " + clock.millis());
Clock clock2 = Clock.system(ZoneId.of("Asia/Shanghai"));
System.out.println("亚洲上海此时的时间戳:"+clock2.millis());
Clock clock3 = Clock.system(ZoneId.of("America/New_York"));
System.out.println("美国纽约此时的时间戳:"+clock3.millis());
//  当前时间戳 : 1545209277657
//  亚洲上海此时的时间戳:1545209277657
//  美国纽约此时的时间戳:1545209277658
//通过ZonedDateTime类和ZoneId
ZoneId zoneId= ZoneId.of("America/New_York");
ZonedDateTime dateTime=ZonedDateTime.now(zoneId);
System.out.println("美国纽约此时的时间 : " + dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")));
System.out.println("美国纽约此时的时间 和时区: " + dateTime);
//  美国纽约此时的时间 : 2018-12-19 03:52:22.494
// 美国纽约此时的时间 和时区: 2018-12-19T03:52:22.494-05:00[America/New_York]

Java 8日期时间API总结:

  • 提供了javax.time.ZoneId 获取时区。
  • 提供了LocalDate和LocalTime类。
  • Java 8 的所有日期和时间API都是不可变类并且线程安全,而现有的Date和Calendar API中的java.util.Date和SimpleDateFormat是非线程安全的。
  • 主包是 java.time,包含了表示日期、时间、时间间隔的一些类。里面有两个子包java.time.format用于格式化, java.time.temporal用于更底层的操作。
  • 时区代表了地球上某个区域内普遍使用的标准时间。每个时区都有一个代号,格式通常由区域/城市构成(Asia/Tokyo),在加上与格林威治或 UTC的时差。例如:东京的时差是+09:00。
  • OffsetDateTime类实际上组合了LocalDateTime类和ZoneOffset类。用来表示包含和格林威治或UTC时差的完整日期(年、月、日)和时间(时、分、秒、纳秒)信息。
  • DateTimeFormatter 类用来格式化和解析时间。与SimpleDateFormat不同,这个类不可变并且线程安全,需要时可以给静态常量赋值
  • DateTimeFormatter类提供了大量的内置格式化工具,同时也允许你自定义。在转换方面也提供了parse()将字符串解析成日期,如果解析出错会抛出DateTimeParseException。DateTimeFormatter类同时还有format()用来格式化日期,如果出错会抛出DateTimeException异常。
  • 再补充一点,日期格式“MMM d yyyy”和“MMM dd yyyy”有一些微妙的不同,第一个格式可以解析“Jan 2 2014”和“Jan 14 2014”,而第二个在解析“Jan 2 2014”就会抛异常,因为第二个格式里要求日必须是两位的。如果想修正,你必须在日期只有个位数时在前面补零,就是说“Jan 2 2014”应该写成 “Jan 02 2014”

② Java 9

模块系统(Jigsaw),新的Java编程组件,用来收集Java代码(类和包)。

REPL (JShell),交互式编程环境。

HTTP 2 客户端,HTTP/2 标准是 HTTP 协议的最新版本。

集合工厂方法,List,Set 和 Map 接口中,新的静态工厂方法可以创建这些集合的不可变实例。

私有接口方法,在接口中使用private私有方法。我们可以使用 private 访问修饰符在接口中编写私有方法。

Process API 改进,改进的 API 来控制和管理操作系统进程。

Stream API 改进,添加新方法满足复杂查询。

try-with-resources 改进, 使用 final 变量时的优化。

匿名类改进,允许使用钻石操作符(Diamond Operator)。

多分辨率图像 API,定义多分辨率图像API,用于操作和展示不同分辨率图像。

轻量级的 JSON API,内置了一个轻量级的 JSON API。

响应式流(Reactive Streams) API,新的响应式流 API 来支持 Java 9 中的响应式编程。

https://openjdk.org/projects/jdk9/

③ Java 10

局部变量类型推断。

整合 JDK 代码仓库。

统一的垃圾回收结构。

并行全垃圾回收器 G1。

应用程序类数据共享。

JVM 线程局部管控。

移除 Native-Header 自动生成工具。

使用附加的 Unicode 语言标记扩展。

JVM 能够适用于不同类型的存储机制的堆,在可选内存设备上进行堆内存分配。

开启了基于 Java 的 JIT 编译器 Graal。

根证书认证。

https://openjdk.org/projects/jdk/10/

④ Java 11

基于嵌套(Nest-Based)的访问控制。

HttpClient 升级,标准化 HTTP 客户端 API。

字符串API更新,包括 String 的 repeat(),isBlank(),strip(),lines() 等多个方法。

Epsilon 低开销垃圾回收器。

简化启动单个源代码文件的方法,无需编译即可启动单文件程序。

Lambda 表达式中使用局部变量类型推荐。

提供一种低开小的 Java 堆分配采样方法 Heap Profiling。

支持 TLS 1.3 协议。

提供 ZGC 可伸缩低延迟垃圾收集器(实验性)。

提供应用程序和 JVM 故障检查和分析的工具。

弃用 Nashorn JavaScript 引擎、Pack200 Tools and API。

https://openjdk.org/projects/jdk/11/

⑤ Java 12

新增一个 GC 算法 Shenandoah,来减少 GC 暂停时间(实验性功能)。

新增了一套微基准测试套件。

Switch 表达式扩展(预览功能)。

引入 JVM 常量 API。

改进 AArch64 实现,只保留一个 AArch64 实现。

使用默认类数据共享(CDS)存档,改进应用程序的启动时间。

针对 64 位平台,使用默认类列表增强 JDK 构建过程以生成类数据共享(class data-sharing,CDS)档。

可中止的 G1 Mixed GC,如果存在超出暂停目标的可能性,则使其可中止。

增强 G1 GC,空闲时自动将堆内存返回给操作系统。

https://openjdk.org/projects/jdk/12/

⑥ Java 13

对 CDS 进行了进一步的简化、改进和扩展。

增强 ZGC 释放未使用内存。

Socket API 重构。

对 Switch 表达式预览特性做了增强改进。

引入了文本块来解决多行文本的问题。

https://openjdk.org/projects/jdk/13/

⑦ Java 14

instanceof 的模式匹配 (预览)。

增加打包工具 jpackage (预览)。

G1 的 NUMA 内存分配优化。

JFR 事件流。

非原子性的字节缓冲区映射。

友好的空指针异常。

Records (预览)。

Switch表达式 (标准) 引入了新形式标签。

弃用 Solaris 和 SPARC 端口。

移除 CMS(Concurrent Mark Sweep)垃圾收集器。

macOS 系统上的 ZGC。

Windows 系统上的 ZGC。

弃用 ParallelScavenge + SerialOld GC 组合。

移除 Pack200 Tools 和 API。

文本块 (第二个预览版)。

外部存储器 API (Incubator)。

https://openjdk.org/projects/jdk/14

⑧ Java 15

引入 Edwards-Curve 数字签名算法。

封闭类(预览)。

禁用、弃用偏向锁。

Record类型(预览)。

ZGC(正式版) -XX:+UseZGC。

文本块(正式版)。

Shenandoah,一种低停顿的垃圾回收器(正式版本)。

https://openjdk.org/projects/jdk/15

在这里插入图片描述

JDK8

Lambda表达式

 //使用java匿名内部类
  Comparator<Integer> cpt = new Comparator<Integer>() {
      @Override
      public int compare(Integer o1, Integer o2) {
          return Integer.compare(o1,o2);
      }
  };

  TreeSet<Integer> set = new TreeSet<>(cpt);

  System.out.println("=========================");

  //使用JDK8 lambda表达式
  Comparator<Integer> cpt2 = (x,y) -> Integer.compare(x,y);
  TreeSet<Integer> set2 = new TreeSet<>(cpt2);
// java7中  筛选产品为nike的
public  List<Product> filterProductByColor(List<Product> list){
    List<Product> prods = new ArrayList<>();
    for (Product product : list){
        if ("nike".equals(product.getName())){
            prods.add(product);
        }
    }
    return prods;
 }

// 使用 lambda
public  List<Product> filterProductByPrice(List<Product> list){
  	return list.stream().filter(p->"nike".equals(p.getName())).collect(Collectors.toList());  
}

方法引用

//静态引用:格式:Class::static_method
List<String> list = Arrays.asList("a","b","c");
list.forEach(str -> System.out.print(str));
list.forEach(System.out::print);
//构造器调用 构造器方法引用格式:Class::new,调用默认构造器
List<String> list = Arrays.asList("a","b","c");
List<Test> list.stream().map(Test::new).collect(Collectors.toList());

public class Test{
    private final String desc;
  
    public Test(String desc){
      this.desc=desc;
    }
}
//方法调用 格式:instance::method
List<String> list = Arrays.asList("a","b","c");
Test test = new Test();
List<String> list.stream().map(test::toAdd).collect(Collectors.toList());

public class Test{
    private final String desc;
  
    public Test(String desc){
      this.desc=desc;
    }

    public String toAdd(String desc){
        return desc+"add";
    }
}

Stream API

// 使用jdk1.8中的Stream API进行集合的操作
@Test
public void test(){

    // 循环过滤元素                                       
    proList.stream()
           .fliter((p) -> "红色".equals(p.getColor()))
           .forEach(System.out::println);

    // map处理元素然后再循环遍历
    proList.stream()
           .map(Product::getName)
           .forEach(System.out::println);
  
   // map处理元素转换成一个List
   proList.stream()
           .map(Product::getName)
           .collect(Collectors.toList());
}

接口中的默认方法和静态方法

public interface ProtocolAdaptor {

    ProtocolAdaptor INSTANCE = DynamicLoader.findFirst(ProtocolAdaptor.class).orElse(null);

   
    default ProtocolAdaptor proxy() {
        return (ProtocolAdaptor) Proxy.newProxyInstance(ProtocolAdaptor.class.getClassLoader(),
                new Class[]{ProtocolAdaptor.class},
                (proxy, method, args) -> intercept(method, args));
    }
}  

Optional

  public String getDesc(Test test){
          return Optional.ofNullable(test)
                  .map(Test::getDesc).else("");
  }

JDK9

创建不可变的集合

/**
	之前方式
*/
public List<String> fruits() {
 List<String> fruitsTmp = new ArrayList<>();
 fruitsTmp.add("apple");
 fruitsTmp.add("banana");
 fruitsTmp.add("orange");
 return Collections.unmodifiableList(fruitsTmp);
}

public Map<Integer, String> numbers() {
 Map<Integer, String> numbersTmp = new HashMap<>();
 numbersTmp.put(1, "one");
 numbersTmp.put(2, "two");
 numbersTmp.put(3, "three");
 return Collections.unmodifiableMap(numbersTmp);
}

/**
	新特性
*/
List<String> fruits = List.of("apple", "banana", "orange");
Map<Integer, String> numbers = Map.of(1, "one", 2,"two", 3, "three");

public List<String> fruitsFromArray() {
	 String[] fruitsArray = {"apple", "banana", "orange"};
	 return Arrays.asList(fruitsArray);
}

接口中的私有方法

public interface ExampleInterface {

    private void printMsg(String methodName) { //接口中的私有方法
        System.out.println("Calling interface");
        System.out.println("Interface method: " + methodName);
    }

    default void method1() {
        printMsg("method1");
    }

    default void method2() {
        printMsg("method2");
    }
}

JDK10

Optional的orElseThrow 方法


public Person getPersonByIdOldWay(Long id) {
	 Optional<Person> personOpt = repository.findById(id);
	 if (personOpt.isPresent())
	  	return personOpt.get();
	 else
	  	throw new NoSuchElementException();
}


/**
	新特性
*/
public Person getPersonById(Long id) {
	 Optional<Person> personOpt = repository.findById(id);
	 return personOpt.orElseThrow();//抛出NoSuchElementException,否则,它返回一个值
}


Optional的 isPresent方法,存在一个值,它将使用该值执行给定的操作。否则,它将执行给定的基于空的操作

//Java8
public void printPersonByIdOldWay(Long id) {
	 Optional<Person> personOpt = repository.findById(id);
	 if (personOpt.isPresent())
	  	System.out.println(personOpt.get());
	 else
	  	System.out.println("Person not found");
}

/**
	新特性
*/
public void printPersonById(Long id) {
	 Optional<Person> personOpt = repository.findById(id);
	 personOpt.ifPresentOrElse(
		   System.out::println,
		   () -> System.out.println("Person not found")
	 );
}

JKD10&&JDK11

var类型推断

public String sumOfString() {
	 BiFunction<String, String, String> func = (var x, var y) -> x + y;
	 return func.apply("abc", "efg");
}

JDK12

switch表达式

 public String newMultiSwitch(int day) {
        return switch (day) {
            case 1, 2, 3, 4, 5 -> "workday";
            case 6, 7 -> "weekend";
            default -> "invalid";
        };
    }

JDK13

文本块

  public String getNewPrettyPrintJson() {
        return """
               {
                    "firstName": "Piotr",
                    "lastName": "Mińkowski"
               }
               """;
    }

JDK14

Records自动创建toString,equals和hashCode方法。实际上,您只需要定义如下所示的字段即可

public record Person(String name, int age) {
}

JDK15

密封类功能,您可以限制超类的使用。使用new关键字,sealed您可以定义哪些其他类或接口可以扩展或实现当前类

public abstract sealed class Pet permits Cat, Dog {

}

public final class Cat extends Pet {//允许的子类必须定义一个修饰符。如果不想允许任何其他扩展名,则需要使用final关键字

}

public non-sealed class Dog extends Pet { //使用non-sealed修饰符,可以打开扩展类

}

//下面的可见声明是不允许的
public final class Tiger extends Pet {}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值