1: Stream的三个操作步骤:
1:创建 Stream
2:中间操作
3:中止操作
/**
* 终结操作
* 判断是否所有的元素都符合条件
*/
boolean b = appAdministrators.stream()
.allMatch(x -> x.getId() < 7);
System.err.println(b);
/**
* 终结操作
* 判断集合中是否满足条件的元素,有则true
*/
boolean b1 = appAdministrators.stream()
.anyMatch(x -> x.getId() > 7);
System.err.println(b1);
/**
* 条件查询元素
* //获取最小的元素
*/
Optional first = appAdministrators.stream()
.sorted((x, y) -> x.getId() - y.getId())
.findFirst();
first.ifPresent(x -> System.err.println(x));
AtomicReference count = new AtomicReference<>(0);
appAdministrators.stream()
.distinct()
.forEach(x-> count.set(count.get() + x.getId()));
System.err.println(count);
/**
* 终结操作
* 消费函数接口
*/
appAdministrators.stream()
.forEach(x -> System.err.println(x));
/**
* 终结操作
* 查询元素数量
*/
long count = appAdministrators.stream()
.distinct()
.count();
System.err.println(count);
/**
* 求元素中的最大值,需要传根据什么比较
* 跟排序条件差不多
*/
Optional max = appAdministrators.stream()
.max((x, y) -> x.getId() - y.getId());
System.err.println(max);
/**
* 求元素中的最小值,需要传根据什么比较
* 跟排序条件差不多
*/
Optional min = appAdministrators.stream()
.min((x, y) -> x.getId() - y.getId());
System.err.println(min);
/**
* 终结操作
* 把集合中的一列转换成list集合返回
*/
List collect = appAdministrators.stream()
.map(x -> x.getUserName())
.collect(Collectors.toList());
System.err.println(collect);
/**
* 终结操作
* 把集合中的一列转换成Set集合返回
*/
Set collect1 = appAdministrators.stream()
.map(x -> x.getUserName())
.collect(Collectors.toSet());
System.err.println(collect);
/**
* 终结操作
* 把集合中的一列转换成map集合返回
*/
appAdministrators.stream()
//key value需要放的数据
.distinct()
.collect(Collectors.toMap(x -> x.getUserName(), y -> y.getAddTime()));
System.err.println(collect);
/**
* 操作集合中的集合
*/
appAdministrators.stream()
.flatMap(x->x.getList().stream())
.distinct()
.filter(y ->y.getUserName().equals("d"))
.forEach(y-> System.err.println(y));
/**
* 操作集合中的集合元素
*/
appAdministrators.stream()
.flatMap(x->x.getList().stream())
//获取到集合中的集合对象转换成流对象
.forEach(x-> System.err.println(x));
/**
* skip 跳过最大id的元素
*/
appAdministrators.stream()
.distinct()
.sorted((x,y)->y.getId()-x.getId())
.skip(1)
.forEach(x-> System.err.println(x));
/**
* 截取limit
*/
appAdministrators.stream()
.distinct()
.sorted((x, y) -> y.getId() - x.getId())
.limit(2)
.forEach(x -> System.err.println(x.getId()));
//把集合转换成流
appAdministrators.stream()
.distinct()
.filter(x -> x.getId() < 100)
.forEach(x -> System.err.println(x.getUserName()));
//去重
appAdministrators.stream()
.distinct()
.forEach(x -> System.err.println(x.getUserName()));
//升序根据id sorted
appAdministrators.stream()
.sorted((x, y) -> x.getId() - y.getId())
.forEach(x -> System.err.println(x.getId()));
//降序根据id sorted
appAdministrators.stream()
.sorted((x, y) -> y.getId() - x.getId())
.forEach(x -> System.err.println(x.getId()));