一.流不是对所有的元素都进行第一次操作接着进行第二次操作,而是对于一个元素执行完所有操作,所有操作都具有短路运算 跟java && || 运算符一致
伪代码:
list.stream().mapToInt(item -> {int lengt = item.length();System.out.println(item);
return length;}).filter(length -> length == 5).findFirst().isPresent(System.out : println)
二.flatMap 将多个stream的多个元素里合并成一个stream
伪代码:
list.stream().map(item -> item.spilt(" ")).flatMap(Arrays::stream).distinct().collect(Collectors.toList())复制代码
伪代码:
Listreuslt = list.stream().flatMap.flatMap(item->list2.stream().map(item2->item+""+item2)).collect(collectors.toList());复制代码
三.分组和分区
申明一个student类,stream可以使用Collectors.groupingBy(Student::getName))来根据学生姓名分组,类似与sql语句的group by
分组:
Map<String,List<Student>> map = students.stream().collect(Collectors.groupingBy(Student::getName));
Map<Integer,List<Student>>map = students.stream().collect(Collectors.groupingBy(Student::getScore));Map<String,Long>map = student.stream().collect(Collectors.groupingBy(Student::getName,Collectors.counting());
Map<String,Double>map = students.stream().collect(Collectors.groupingBy(Student::getName,Collectors.averagingDouble(Student::getScore)));
多级分组:
Map<Integer,Map<String,List<Student>>> map = students.Stream().collect(groupingBy(Student::getScore,groupinBy(Student::getName)))
分区:
Map<Boolean,List<Student>> map = students.stream().collect(Collectors.partitioningBy(student->student.getScore()>=90));
多级分区:
Map>> map = students.stream().collect(partitioningBy(student -> student.getScore()>80,partitionBy(student -> student.getScore()>90)));复制代码
jdk 实现的方式越具体越好,比如由student创建的集合的长度计算可以直接用 .size()方法得出,但是jdk提供了许多实现的方法,其中方法越具体其扩展性越高,比如我可以得到student创建的集合里去重人名的集合长度