Stream API
- 筛选:filter(Class:isXXX())
- 排序
//按年龄升序
.sorted(Comparator.comparing(Student::getAge))
//按年龄降序
.sorted(Comparator.comparing(Student::getAge).reversed())
public void sortUserInfoList(List userInfoList){
userInfoList.sort((user1, user2) -> {
Long userId1 = user1.getUserId();
Long userId2 = user2.getUserId();
return userId1.compareTo(userId2);
});
}
- 消重:distinct()
- 截短:limit(2)
- 跳过:skip(2)
- 映射:map(Class:getXXX())--eg. map(String:length)
word = ["Hello","World"]
map(word->word.split("")) ~~~~~{[H,e,l,l,o],[W,o,r,l,d]}
//降维扁平化
flatMap(word->word.split(""))~~~~~{H,e,l,l,o,W,o,r,l,d}
//集合转list
.collect(Collectors.toList())
//集合转set
.collect(Collectors.toSet())
//集合转map
.collect(Collectors.toMap(a->a,b->b))
- 至少一个匹配:anyMatch(Class:isXXX())
- 所有全部匹配:allMatch(Class:isXXX())
- 没有任何匹配:noneMatch(Class:isXXX())
//没有值相等时返回true
boolean cc = strs.stream().noneMatch(str -> str.equals("a"));
- 返回任意元素:findAny()
- 返回第一元素:findFirst()
IntStream | DoubleStream | LongStream:数值流
//构建IntStream,使用builder并单个添加元素
IntStream intStream = IntStream.builder().add(1).build();
//无限流 和limit连用
intStream = IntStream.generate(()-> (int) (Math.random()*10000));
intStream = intStream.limit(5);
//迭代无限流 和limit连用
intStream = IntStream.iterate(2,n->n*3);
intStream = intStream.limit(5);
//of方法把一组值变成流
intStream = IntStream.of(1,2,3);
//两个数之间的整数流 左闭右开
intStream = IntStream.range(1,5);
//两个数之间的整数流 全闭 跳过前2个
intStream = IntStream.rangeClosed(1,5).skip(2);
//将两个流合并为一个
IntStream otherIntStream = IntStream.of(1,2,3);
intStream = IntStream.concat(intStream,otherIntStream);
//循环遍历
intStream.forEach(System.out::println);
//升序遍历
intStream.sorted().forEach(System.out::println);
//降序 先要用boxed方法转成包装类型
intStream.boxed().sorted(Comparator.reverseOrder()).forEach(System.out::println);
//peek操作流返回值仍为IntStream,只有关闭流时才会执行
System.out.println(intStream.peek(System.out::println).sum());
//流转数组
int[] array = intStream.toArray();
System.out.println(array);
//转double流,long流同理
DoubleStream doubleStream = intStream.asDoubleStream();
doubleStream.forEach(System.out::println);
//映射为double流
DoubleStream doubleStream =intStream.mapToDouble(i->i);
doubleStream.forEach(System.out::println);
//计数
long count = intStream.count();
System.out.println(count);
//求和
int sum = intStream.sum();
System.out.println(sum);
//规约
int reduce = intStream.reduce(0,(a,b)->a+b);
System.out.println(reduce);
并行流
- 流的顺序化和并行化:sequential()/parallel(),同时出现多种时以最后一次为准
//iterator得到的流串行效率高
LongStream.iterate(1L,i -> i+1).limit(10000000L).parallel().reduce(0L,Long:sum)
//range得到得流并行效率高
LongStream.range(0L, 100000000L).parallel().reduce(0L,Long::sum);
lambda
//实现Runnable接口
new Thread(()-> System.out.println("hello,world!")).start();
//实现Comparator接口
Collections.sort(list,(a,b)->a.charAt(0)>b.charAt(0)?1:-1);
//Predicate,对参数进行预测,返回true|false
String name = "zhoupei";
Predicate predicate = s -> name.equals(s);
list.stream().filter(predicate);
//Consumer,对参数执行无返回值的回调
private static void execute(Consumer consumer){
String name = "zhoupei";
System.out.println("执行任务");
consumer.accept(name);
}
execute(s-> System.out.println("回调打印我的名字:" + s));
//Function,对参数执行有返回值的回调
Function function = i-> 1*5;
System.out.println(function.apply(3));
方法引用
//调用类的静态方法
ClassName::staticMethod
//引用对象的方法
String:length
//调用已经存在的外部对象的方法
Transaction::getValue
实践案例
List list1 = new ArrayList(){{
add("lisi");
add("wangwu");
}};
List list2 = new ArrayList(){{
add("zhangsan");
add("lisi");
add("wangwu");
}};
list1.forEach(s1->list2.forEach(s2->{
if (s1.equals(s2)){
System.out.println(s2);
}
}));
Optional
-
ofNullable
,创建一个可以为空的Optional对象
Optional optional = Optional.ofNullable("hello world");
-
ifPresent
,如果Optional对象不为空才执行逻辑
optional.ifPresent(s -> System.out.println(true));
-
orElse
,创建一个有默认值的对象(orElse里的内容一定会执行)
String string = Optional.ofNullable("hello world").orElse("default");
-
orElseGet
,创建一个有默认值的对象(如果前面不为空,orElseGet里的内容不会执行)
String string = Optional.ofNullable("hello world").orElseGet(()->"default");
boolean exists = optional.filter(predicate1.and(predicate2)).isPresent();
optional.filter(predicate1.and(predicate2)).ifPresent(s-> System.out.println(true));
- 实战:去掉hello world中间的空格,然后校验长度|判断是否相等
Predicate predicate3 = s->"helloworld".equals(s);
optional.map(s -> s.replace(" ",""))
.filter(predicate1.and(predicate2).and(predicate3))
.ifPresent(s-> System.out.println(true));
--各种复合:比较器复合、谓词复合、函数复合(待充电)