這是Stream
操做中的最後一步,終止操做,終止操做會從流的流水線生成結果。其結果能夠是任何不是流的值,例如:List
,Integer
,void
java
方法名 | 介紹 | 返回類型 |
---|---|---|
allMatch | 檢查是否匹配全部元素 | boolean |
anyMatch | 檢查是否至少匹配一個元素 | boolean |
noneMatch | 檢查是否沒有匹配全部元素 | boolean |
findFirst | 返回第一個元素 | Optional |
findAny | 返回當前流中的任意元素 | Optional |
count | 返回流中元素總個數 | |
max | 返回流中最大值 | |
min | 返回流中最小值 |
package java8; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; /** * @Description: * @Date: 2020/7/15 00:04 * @Auther: zhaodi */ public class StreamDemo01 { public static void main(String[] args) { List<Student> studentList = new ArrayList<>(); studentList.add(new Student(1, "趙迪", 23)); studentList.add(new Student(3, "tom", 25)); studentList.add(new Student(2, "tom", 27)); studentList.add(new Student(2, "rose", 22)); Comparator<Student> comparator = Comparator.comparingInt(Student::getId); List<Student> list = studentList.stream().sorted(comparator).collect(Collectors.toList()); System.out.println(list); Boolean success = list.stream().allMatch(x -> x.getId() > 1); System.out.println(success); // false Boolean success1 = list.stream().anyMatch(x -> x.getId() > 2); System.out.println(success1); // true Boolean success2 = list.stream().noneMatch(x -> x.getId() == 2); System.out.println(success2);//false Optional<Student> op = list.stream().sorted(comparator).findFirst(); Student student = op.get(); System.out.println(student); Optional<Student> optional = list.stream().findAny(); long count = list.stream().count(); System.out.println(count); Optional<Student> opMax = list.stream().max(comparator); Optional<Student> opMin = list.stream().min(comparator); } }
方法名 | 介紹 | 返回類型 |
---|---|---|
reduce(BinaryOperator b) | 能夠將流中元素反覆結合起來,獲得一個Optional對象 | Option
|
reduce(T iden,BinaryOperator b) | 能夠將流中元素反覆結合起來,獲得一個值 | T |
reduce
方法很是的通用,後面介紹的count
,sum
等均可以使用其實現。reduce
方法有三個重載的方法,本文介紹兩個最經常使用的,最後一個留給讀者本身學習。先來看reduce
方法的第一種形式,其方法定義以下ide
第一種函數
Optional<T> reduce(BinaryOperator<T> accumulator);
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9); Optional<Integer> optional= list.stream().reduce((x, y) -> x + y); System.out.println(optional.get()); // 45
能夠看到reduce
方法接受一個函數,這個函數有兩個參數,第一個參數是上次函數執行的返回值(也稱爲中間結果),第二個參數是stream
中的元素,這個函數把這兩個值相加,獲得的和會被賦值給下次執行這個函數的第一個參數。要注意的是:第一次執行的時候第一個參數的值是Stream的第一個元素,第二個參數是Stream的第二個元素。這個方法返回值類型是Optional
,這是Java8
防止出現NPE
的一種可行方法,後面的文章會詳細介紹,這裏就簡單的認爲是一個容器,其中可能會包含0個或者1個對象學習
第二種code
T reduce(T identity, BinaryOperator<T> accumulator);
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9); Integer sum = list.stream().reduce(0, (x, y) -> x + y); System.out.println(sum);
這個定義上上面已經介紹過的基本一致,不一樣的是:它容許用戶提供一個循環計算的初始值,若是Stream
爲空,就直接返回該值。並且這個方法不會返回Optional
,由於其不會出現null
值對象
如上面代碼所示:接口
若是list
集合裏面沒有一個對象的話,那麼第一種寫法會報錯,第二種結果則是0ip
備註get
map
和reduce
的鏈接一般稱爲map-reduce
模式,例如string
List<Student> studentList = new ArrayList<>(); studentList.add(new Student(1, "趙迪", 23)); studentList.add(new Student(3, "tom", 25)); studentList.add(new Student(2, "tom", 27)); studentList.add(new Student(2, "rose", 22)); Optional sum = studentList.stream().map(x -> x.getAge()).reduce((x, y) -> x + y);
方法名 | 介紹 | 返回類型 |
---|---|---|
collect(Collector c) |
將流轉換爲其它形式。接受一個Collector 接口的實現,用於給Stream 中元素作彙總方法 |
Collector
接口中的方法的實現決定了如何對流執行收集操做(如收集到List
、Set
、Map
)。
可是Collectors
實現類提供了不少靜態方法,能夠方便的建立常見收集器實例,具體方法和實例以下
方法名 | 介紹 | 返回類型 |
---|---|---|
Collectors.toList() |
將流轉換爲List
|
List<T> |
Collectors.toSet() |
將流轉換爲Set
|
Set<T> |
Collectors.toCollection(LinkedList::new) |
將流轉換爲集合 | |
Collectors.toMap(Student::getName, Student::getAge, (e, r) -> r) |
轉爲Map,具體見下面代碼 | Map<String,Object> |
Collectors.counting() |
統計個數 | Long |
Collectors.averagingDouble(Student::getAge) |
求平均值 | Double |
Collectors.summingInt(Student::getAge) |
求和 | Integer |
Collectors.maxBy(Comparator c) |
最大值 | Optional<T> |
Collectors.minBy(Comparator c) |
最小值 | Optional<T> |
Collectors.groupingBy(Student::getName) |
單個分組 | Map<String,List<T> |
Collectors.partitioningBy(x->x.getAge()>26) |
分區 | Map<Boolean>,List<T> |
Collectors.summarizingDouble(Student::getAge) |
統計分析 | DoubleSummaryStatistics |
package java8; import java.util.*; import java.util.stream.Collectors; /** * @Description: * @Date: 2020/7/15 00:04 * @Auther: zhaodi */ public class StreamDemo01 { public static void main(String[] args) { List<Student> studentList = new ArrayList<>(); studentList.add(new Student(1, "趙迪", 23)); studentList.add(new Student(3, "tom", 25)); studentList.add(new Student(2, "tom", 27)); studentList.add(new Student(2, "rose", 22)); // 轉List List<Student> newList = studentList.stream().filter(x -> x.getAge() > 23).collect(Collectors.toList()); System.out.println(newList); //[Student(id=3, name=tom, age=25), Student(id=2, name=tom, age=27)] // 轉Set Set<Student> studentSet = studentList.stream().collect(Collectors.toSet()); System.out.println(studentSet);//[Student(id=3, name=tom, age=25), Student(id=2, name=rose, age=22), Student(id=1, name=趙迪, age=23), Student(id=2, name=tom, age=27)] // 轉集合 studentList.stream().collect(Collectors.toCollection(LinkedList::new)); // 轉Map(e:舊的key,r:新的key,若是存在key重複,則使用新的key或者舊的key均可以) Map<String, Object> studentMap = studentList.stream().collect(Collectors.toMap(Student::getName, Student::getAge, (e, r) -> r)); System.out.println(studentMap); // {tom=27, 趙迪=23, rose=22} // 求個數 Long count = studentList.stream().collect(Collectors.counting()); System.out.println(count); // 平均值 Double avgAge = studentList.stream().collect(Collectors.averagingDouble(Student::getAge)); System.out.println(avgAge); // 求和 Integer ageSum = studentList.stream().collect(Collectors.summingInt(Student::getAge)); System.out.println(ageSum); // 最大值 Comparator<Student> ageComparator = Comparator.comparingInt(Student::getAge); Optional<Student> maxStu = studentList.stream().collect(Collectors.maxBy(ageComparator)); System.out.println(maxStu.get()); // 最小值 Optional<Integer> min = studentList.stream().map(Student::getAge).collect(Collectors.minBy(Integer::compare)); System.out.println(min.get()); // 單個分組(根據姓名分組) Map<String, List<Student>> stringListMap = studentList.stream().collect(Collectors.groupingBy(Student::getName)); System.out.println(stringListMap);//{tom=[Student(id=3, name=tom, age=25), Student(id=2, name=tom, age=27)], 趙迪=[Student(id=1, name=趙迪, age=23)], rose=[Student(id=2, name=rose, age=22)]} // 多級分組(先根據姓名分,在根據年紀分) Map<String, Map<Object, List<Student>>> map = studentList.stream().collect(Collectors.groupingBy(Student::getName, Collectors.groupingBy((x) -> { if (x.getAge() > 26) { return "老年"; } else { return "青年"; } }))); System.out.println(map);//{tom={青年=[Student(id=3, name=tom, age=25)], 老年=[Student(id=2, name=tom, age=27)]}, 趙迪={青年=[Student(id=1, name=趙迪, age=23)]}, rose={青年=[Student(id=2, name=rose, age=22)]}} // 分區(分爲兩個區,年紀大於26和小於等於26) Map<Boolean,List<Student>> partitionStudent = studentList.stream().collect(Collectors.partitioningBy(x->x.getAge()>26)); System.out.println(partitionStudent); //{false=[Student(id=1, name=趙迪, age=23), Student(id=3, name=tom, age=25), Student(id=2, name=rose, age=22)], true=[Student(id=2, name=tom, age=27)]} // 統計分析 DoubleSummaryStatistics dss = studentList.stream().collect(Collectors.summarizingDouble(Student::getAge)); System.out.println(dss.getAverage()); System.out.println(dss.getSum()); System.out.println(dss.getMax()); // 鏈接 String names = studentList.stream().map(Student::getName).collect(Collectors.joining(",")); System.out.println(names); //趙迪,tom,tom,rose } }