stream是元素的集合,类似Iterator,也可以把stream当成一个高级版本的Iterator。原始版本的Iterator只能一个一个的遍历元素;高级版本的Stream,只需要给出需要对其包含的元素执行什么操作,具体这些操作如何应用到每个元素上,就交给Stream即可。
stream()中的源数据可以是集合、数组、I/O文件流、产生器generator等。
1.foreach
//遍历list
list.stream().forEach(entity-> System.out.println(entity.getName));
2.filter
//过滤出符合条件的
list.stream().filter(entity -> StringUtils.equals("张三", entity.getName())).forEach(entity -> System.out.println(entity.getName()));
3.flatMap
//把小的流转成大的流
List<String> collect = list.stream() //获取流
.flatMap(entity-> entity.getNames().stream()) //获取名称流,并合并
.distinct() //去重合并后的名称
.flatMap(name -> Arrays.stream(name.getXing().split("·"))) //获取名字分类,并将分类解析转换为流,合并
.distinct() //分类去重
.collect(Collectors.toList());
4.类似数据库操作
//获取数据中的第一个
//limit索引值类似于数据库,从1开始
list.stream().limit(1).forEach(employee -> System.out.println(employee.getName()));
//去重
list.stream().distinct().forEach(employee -> System.out.println(employee.getName()));
List<Stl> list = list.stream().distinct().collect(Collectors.toList());
//按指定要求排序
list.stream().sorted((e1,e2) -> (int) (e2.getSalary() - e1.getSalary()));
5.skip
//跳过前6条数据并打印名字出来
list.stream().skip(6).forEach(entity-> System.out.println(entity.getName()));
6.关于Collectors
//把用户按照名字分组,key为name值,value为name和key相同的对象集合
Map<String, List<User>> collectGroup = list.stream().collect(Collectors.groupingBy(entity -> entity.getName()));
//Collectors.counting()计算list的size
Long collectCount = list.stream().collect(Collectors.counting());<==>list.stream().count()
//list转换成set,舍弃重复值
Set<User> set = list.stream().collect(Collectors.toSet());
//list转换成map
Map<String, String> map = list.stream().collect(Collectors.toMap(User::getName, User::getPosition));
//计算list中指定属性的平均值
//Collectors.averagingDouble()执行中会把元素看成double,但最终结果为double
//Collectors.averagingInt() 执行中会把元素看成int,但最终结果为double
Double double = list.stream().collect(Collectors.averagingDouble(User::getSalary));
//Collectors.mapping()相当于list.stream().map(),收集name属性
//Collectors.joining()每次收集一次name都在后面加上,最后一次没有
String mapping = list.stream().collect(Collectors.mapping(User::getName, Collectors.joining(",")));
//Collectors.maxBy()求最大值(类似--Collectors.minBy()最小值)
Employee employeeMax = list.stream().collect(Collectors.maxBy((a, b) -> a.getAge() - b.getAge())).get();<==>list.stream().max();
//两数相加
Employee employeeReducing = list.stream().collect(Collectors.reducing((a, b) -> a+b)).get();<==>list.stream().reduce()
7.对整个数组进行处理
User firstUser = list.stream().findFirst().get();<==>list.get(0);
//findAny查找任意一个,如果有多个只会匹配第一个
User findAnyUser = list.stream().findAny().get();
//anyMatch,只要有符合条件的就返回true,默认为false
boolean anyMatch = list.stream().anyMatch(entity -> 27 == entity.getAge());
//allMatch,必须都符合条件的才返回true,默认为true
boolean allMatch = list.stream().allMatch(entity -> 27 == entity.getAge());
//noneMatch,必须全部不匹配才返回true,默认为true
boolean noneMatch = list.stream().noneMatch(entity -> 27 == entity.getAge());