原来的Null值判断
String s = test();
if (null != s) {
System.out.println(s);
}
使用OptionalNull判断
Optional<String> s = Optional.ofNullable(test());
s.ifPresent(System.out::println);
如果为空则赋值
String s = null;
Optional<String> o = Optional.ofNullable(s);
System.out.println(o.orElse("test"));
如果为空则抛异常
String s=null;
Optional<String> o = Optional.ofNullable(s);
System.out.println(o.orElseThrow(()->new Exception("test")));
FlatMap
List<String> list = Arrays.asList("a,b,c", "1,2,3");
Stream<String> s3 = list.stream().flatMap(s -> {
//将每个元素转换成一个stream
String[] split = s.split(",");
Stream<String> s2 = Arrays.stream(split);
return s2;
});
s3.forEach(System.out::println);
Sorted
Student s1 = new Student("aa", 10);
Student s2 = new Student("bb", 20);
Student s3 = new Student("aa", 30);
Student s4 = new Student("dd", 40);
List<Student> studentList = Arrays.asList(s1, s2, s3, s4);
//自定义排序:先按姓名升序,姓名相同则按年龄升序
studentList.stream().sorted(
(o1, o2) -> {
if (o1.getName().equals(o2.getName())) {
return o2.getAge() - o1.getAge();
} else {
return o2.getName().compareTo(o1.getName());
}
}
).forEach(o->System.out.println(o.getName()+o.getAge()));
reduce
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24);
Integer v = list.stream().reduce((x1, x2) -> x1 + x2).get();
System.out.println(v); // 300
Integer v1 = list.stream().reduce(10, (x1, x2) -> x1 + x2);
System.out.println(v1); //310
Integer v3 = list.parallelStream().reduce(0,
(x1, x2) -> {
System.out.println("parallelStream accumulator: x1:" + x1 + " x2:" + x2);
return x1 + x2;
},
(x1, x2) -> {
System.out.println("parallelStream combiner: x1:" + x1 + " x2:" + x2);
return x1 + x2;
});
System.out.println(v3);
reduce函数,第一次执行x1是第一个元素,x2是第二个元素,第2次执行时,x1是上次执行的结果,x2是第3个元素,以此类推。
在并行流(parallelStream)中,我们知道流被fork join出多个线程进行执行,此时每个线程的执行流程就跟第二个方法reduce(identity,accumulator)一样,而第三个参数combiner函数,则是将每个线程的执行结果当成一个新的流,然后使用第一个方法reduce(accumulator)流程进行规约。