Java8新特性
Lamba表达式和函数式接口:
接口里面只能有一个未实现的方法,然后是可以有default和静态方法实现的。
但在用的时候需要重写未实现的方法:
一般是在实现Runnable接口,sort方法里面这样使用:
Arrays.asList("a","b","c").forEach(e->System.out.println(e)); String[] a= {"d","b","c"}; Arrays.asList(a).sort( ( e1, e2 ) -> e1.compareTo( e2 ) );
引用方法:
对象引用::静态方法名
Function<Long, Long> f = Math::abs; Long result = f.apply(-3L);
Math是一个类而abs为该类的静态方法。Function中的唯一抽象方法apply方法参数列表与abs方法的参数列表相同,都是接收一个Long类型参数。
类名::实例方法名
BiPredicate<String, String> b = String::equals; b.test("abc", "abcd");
String是一个类而equals为该类的定义的实例方法。BiPredicate中的唯一抽象方法test方法参数列表与equals方法的参数列表相同,都是接收两个String类型参数。
引用构造器:
Function<Integer, StringBuffer> fun = StringBuffer::new; StringBuffer buffer = fun.apply(10);
Function接口的apply方法接收一个参数,并且有返回值。在这里接收的参数是Integer类型,与StringBuffer类的一个构造方法StringBuffer(int capacity)对应,而返回值就是StringBuffer类型。上面这段代码的功能就是创建一个Function实例,并把它apply方法实现为创建一个指定初始大小的StringBuffer对象。
引用数组:
Function<Integer, int[]> fun = int[]::new; int[] arr = fun.apply(10); Function<Integer, Integer[]> fun2 = Integer[]::new; Integer[] arr2 = fun2.apply(10);
Stream的概念:
将一个Collections转为stream,转为一条执行链,分别处理:
List<String> myList = Arrays.asList("a1", "a2", "b1", "c2", "c1"); myList .stream() .filter(s -> s.startsWith("c")) .map(String::toUpperCase) .sorted() .forEach(System.out::println);
c1 c2
本文来自博客园,作者:LeeJuly,转载请注明原文链接:https://www.cnblogs.com/peterleee/p/10810550.html

浙公网安备 33010602011771号