java 8 stream API<一>

.流不是對全部的元素都進行第一次操做接着進行第二次操做,而是對於一個元素執行完全部操做,全部操做都具備短路運算 跟java && || 運算符一致java

僞代碼: sql

list.stream().mapToInt(item -> {int lengt = item.length();System.out.println(item);bash

return length;}).filter(length -> length == 5).findFirst().isPresent(System.out : println)spa

二.flatMap 將多個stream的多個元素裏合併成一個stream   code

僞代碼: get

list.stream().map(item -> item.spilt(" ")).flatMap(Arrays::stream).distinct().collect(Collectors.toList())複製代碼

僞代碼: string

List<String> reuslt = list.stream().flatMap.flatMap(item->list2.stream().map(item2->item+""+item2)).collect(collectors.toList());複製代碼

三.分組和分區it

申明一個student類,stream能夠使用Collectors.groupingBy(Student::getName))來根據學生姓名分組,相似與sql語句的group byio

分組:class

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<Boolean,Map<Boolean,List<Student>>> map = students.stream().collect(partitioningBy(student -> student.getScore()>80,partitionBy(student -> student.getScore()>90)));複製代碼

jdk 實現的方式越具體越好,好比由student建立的集合的長度計算能夠直接用 .size()方法得出,可是jdk提供了許多實現的方法,其中方法越具體其擴展性越高,好比我能夠獲得student建立的集合裏去重人名的集合長度

相關文章
相關標籤/搜索