1、Java 8 允许我们通过 default 关键字对接口中定义的抽象方法提供一个默认的实现。
如:
default String init();
2、Lambda 表达式
Collections.sort(names, (String a, String b) -> {
return b.compareTo(a);
});
例子代码:
/*filter过滤(T-> boolean)*/
List newlist = list.stream().filter(user -> user.getAge() > 20) .collect(Collectors.toList());
/*distinct 去重*/
List newlist = list.stream().distinct().collect(Collectors.toList());
/*sorted排序*/
List newlist = list.stream() .sorted(Comparator.comparingInt(User::getAge)).collect(Collectors.toList());
/*limit返回前n个元素*/
List newlist = list.stream() .sorted(Comparator.comparingInt(User::getAge)).limit(2).collect(Collectors.toList());
/*skip去除前n个元素*/
List newlist = list.stream() .sorted(Comparator.comparingInt(User::getAge)).skip(2).collect(Collectors.toList());
/*map(T->R)*/
List newlist = list.stream() .map(User::getName).distinct().collect(Collectors.toList());
/*allMatch(T->boolean)
检测是否全部满足参数行为*/
boolean flag = list.stream().allMatch(user -> user.getAge() >= 10);
/*anyMatch(T->boolean)
检测是否有任意元素满足给定的条件*/
boolean flag = list.stream() .anyMatch(user -> user.getAge() == 10);
/*noneMatchT->boolean)
流中是否有元素匹配给定的 T -> boolean条件*/
boolean flag = list.stream() .noneMatch(user -> user.getName().contains("张三李四"));
/*findFirst( ):找到第一个元素*/
Optional optionalUser = list.stream() .sorted(Comparator.comparingInt(User::getAge)) .findFirst();
/*count()计算总数*/
long count = list.stream().count();
/*最大值最小值*/
Optional max = list.stream() .collect( Collectors.maxBy( Comparator.comparing(User::getAge) ) );
Optional min = list.stream() .collect( Collectors.minBy( Comparator.comparing(User::getAge) ) );
/*求和_平均值*/
int totalAge = list.stream() .collect(Collectors.summingInt(User::getAge));
double avgAge = list.stream() .collect(Collectors.averagingInt(User::getAge));
/*一次性得到元素的个数、总和、最大值、最小值*/
IntSummaryStatistics statistics = list.stream() .collect(Collectors.summarizingInt(User::getAge));
/*拼接*/
String names = list.stream() .map(User::getName) .collect(Collectors.joining(", "));
/*分组*/
Map> map1 = users().stream() .collect(Collectors.groupingBy(User::getName));
Map>> map2 = users().stream() .collect(Collectors.groupingBy(User::getName, Collectors.groupingBy(User::getAge)));
/*分组合计*/
Map num = users().stream() .collect(Collectors.groupingBy(User::getName, Collectors.counting()));
Map num2 = users().stream() .filter(user -> user.getAge() >= 18) .collect(Collectors.groupingBy(User::getName, Collectors.counting()));