Stream
Reduction, 给N个数值,求出其总和/最大值/最小值/均值这一类的操作,称为Reduction
Option
Optional
类是一个可以为null
的容器对象。如果值存在则isPresent()
方法会返回true
,调用get()
方法会返回该对象。
Optional 类的引入很好的解决空指针异常
1、ofNullable可以null
2、of不可以null
3、isPresent判断是否存在
4、orElse存在返回,不存在返回0
5、get()获得值
public class Java8Tester {
public static void main(String args[]){
Java8Tester java8Tester = new Java8Tester();
Integer value1 = null;
Integer value2 = new Integer(10);
// Optional.ofNullable - 允许传递为 null 参数
Optional<Integer> a = Optional.ofNullable(value1);
// Optional.of - 如果传递的参数是 null,抛出异常 NullPointerException
Optional<Integer> b = Optional.of(value2);
System.out.println(java8Tester.sum(a,b));
}
public Integer sum(Optional<Integer> a, Optional<Integer> b){
// Optional.isPresent - 判断值是否存在
System.out.println("第一个参数值存在: " + a.isPresent());
System.out.println("第二个参数值存在: " + b.isPresent());
// Optional.orElse - 如果值存在,返回它,否则返回默认值
Integer value1 = a.orElse(new Integer(0));
//Optional.get - 获取值,值需要存在
Integer value2 = b.get();
return value1 + value2;
}
}
Comparator
1.普通排序
List<FileListDto> sortList = fileList.stream()
.sorted(FileListDto::getPriceEnableVendor).collect(Collectors.toList());
2.有空值的排序
List<FileListDto> sortList = fileList.stream()
.sorted(Comparator.comparing(FileListDto::getPriceEnableVendor, Comparator.nullsLast(String::compareTo))).collect(Collectors.toList());