話不多說,自己挖的坑自己要填完,今天就給大家講完Java8中Stream的終端操作使用詳解。Stream流的終端操作主要有以下幾種,我們來一一講解。
- forEach()
- forEachOrdered()
- toArray()
- reduce()
- collect()
- min()
- max()
- count()
- anyMatch()
- allMatch()
- noneMatch()
- findFirst()
- findAny()
終端操作代碼實例詳解
1、forEach():遍歷流中的每一個元素,按照指定的方法執行,執行順序不一定按照流的順序。
// foreach:遍歷流中每一個元素,執行順序按照流的順序 Stream.of(1,2,3,4,5,6).forEach(System.out::println); // foreach:遍歷流中每一個元素,執行順序不一定按照流的順序,.parallel()表示創建一個並行流 Stream.of(1,2,3,4,5,6).parallel().forEach(System.out::println);
運行結果:
1
2
3
4
5
6
2
1
6
5
3
4
2、forEachOrdered():遍歷流中的每一個元素,按照指定的方法執行,執行順序按照流的順序。
// forEachOrdered():遍歷流中每一個元素,執行順序按照流的順序 Stream.of(1,2,3,4,5,6).forEachOrdered(System.out::println); // forEachOrdered:遍歷流中每一個元素,執行順序按照流的順序,.parallel()表示創建一個並行流 Stream.of(1,2,3,4,5,6).parallel().forEachOrdered(System.out::println);
運行結果:
1
2
3
4
5
6
1
2
3
4
5
6
3、toArray():將流中的元素放入到一個數組中
// toArray():將流中的元素放入到一個數組中 String[] strings = Stream.of("ma", "zhi", "chu").toArray(String[]::new); System.out.println(Arrays.toString(strings));
運行結果:[ma, zhi, chu]
4、reduce():這個方法的主要作用是把 Stream 元素組合起來。它提供一個起始值(種子),然后依照運算規則(BinaryOperator),和前面 Stream 的第一個、第二個、第 n 個元素組合。從這個意義上說,字符串拼接、數值的 sum、min、max、average 都是特殊的 reduce。
// reduce():字符串拼接 String reduceStr1 = Stream.of("ma", "zhi", "chu").reduce("", String::concat); String reduceStr2 = Stream.of("ma", "zhi", "chu").reduce("", (x,y)->x+y); System.out.println(reduceStr1); System.out.println(reduceStr2); // reduce():求和,identity(起始值)為0 Integer total1 = Stream.of(1,2,3,4).reduce(0, Integer::sum); Integer total2 = Stream.of(1,2,3,4).reduce(0, (x, y) -> x +y); System.out.println(total1); System.out.println(total2); // 求和,sumValue = 10, 無起始值 Integer total3 = Stream.of(1, 2, 3, 4).reduce(Integer::sum).get(); System.out.println(total3); // reduce():求最小值 double minValue = Stream.of(-1.1, 8.8, -2.2, -6.6).reduce(Double.MAX_VALUE, Double::min); System.out.println(minValue);
運行結果:
mazhichu
mazhichu
10
10
10
-6.6
5、collect():是Stream的一個函數,負責收集流。前面我們說中間操作是將一個流轉換成另一個流,這些操作是不消耗流的,但是終端操作會消耗流,產生一個最終結果,collect()就是一個規約操作,將流中的結果匯總。結果是由傳入collect()中的Collector定義的。
// collect():負責收集流,將結果匯總,比如將下面的流中的結果匯總到一個集合中去 List<Integer> skipNum = IntStream.range(1,100).skip(90) .boxed() .collect(Collectors.toList()); System.out.println(skipNum);
運行結果:[91, 92, 93, 94, 95, 96, 97, 98, 99]
6、min():返回流中的最小值
// min():返回流中的最小值 List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5, 6); Integer minNum = nums.stream().min(Integer::compareTo).get(); Integer min = nums.stream().min((x,y) -> x.compareTo(y)).get(); System.out.println(minNum); System.out.println(min);
運行結果:
1
1
7、max():返回流中的最大值
// max():返回流中的最大值 List<Integer> num = Arrays.asList(1, 2, 3, 4, 5, 6); Integer maxNum = num.stream().max(Integer::compareTo).get(); Integer max = num.stream().max(Comparator.comparing(Function.identity())).get(); System.out.println(maxNum); System.out.println(max);
運行結果:
6
6
8、count():返回流中元素的數量
// count():返回流中元素的數量 List<Integer> ls = Arrays.asList(1,2,3,4,5); long count = ls.stream().count(); long count1 = ls.stream().filter(l -> l > 2).count(); System.out.println(count); System.out.println(count1);
運行結果:
5
3
9、anyMatch():Stream 中只要有一個元素符合傳入的斷言,就返回 true,否則返回false。
// anyMatch():判斷流中數據是否有一個復合斷言 List<Integer> ins = Arrays.asList(1,2,3,4,5); boolean b = ins.stream().anyMatch(l -> l > 2); boolean b1 = ins.stream().anyMatch(l -> l > 5); System.out.println(b); System.out.println(b1); // anyMatch():判斷流中數據是否有一個復合斷言,如果流為空,永遠返回false List<Integer> inss = Arrays.asList(); boolean b2 = inss.stream().anyMatch(l -> l > 2); System.out.println(b2);
運行結果:
true
false
false
10、allMatch():Stream 中所有元素都符合傳入的斷言時返回 true,否則返回false,流為空時總是返回true。
// allMatch():判斷流中元素是否都符合斷言條件 List<Integer> ints = Arrays.asList(1,2,3,4,5); boolean c = ints.stream().allMatch(l -> l > 0); boolean c1 = ints.stream().allMatch(l -> l > 1); System.out.println(c); System.out.println(c1); // allMatch():判斷流中元素是否都符合斷言條件,如果流為空,永遠返回true List<Integer> emptyList = new ArrayList<>(); boolean c2 = emptyList.stream().allMatch(e -> e > 1); System.out.println(c2);
運行結果:
true
false
true
11、noneMatch():Stream 中所有元素都不滿足傳入的斷言時返回 true,否則返回false。
// noneMatch():判斷流中元素是否都不符合傳入的斷言條件 List<Integer> numList = Arrays.asList(1,2,3,4,5); boolean d = numList.stream().noneMatch(l -> l > 6); boolean d1 = numList.stream().noneMatch(l -> l > 1); System.out.println(d); System.out.println(d1); // noneMatch():判斷流中元素是否都不符合傳入的斷言條件,流為空時永遠返回true List<Integer> numist = Arrays.asList(); boolean d2 = numist.stream().noneMatch(l -> l > 6); System.out.println(d2);
運行結果:
true
false
true
12、findFirst():總是返回流中的第一個元素,如果流為空,返回一個空的Optional.
// findFirst():返回流中的第一個元素 List<Integer> integers = Arrays.asList(1, 2, 3); Optional<Integer> first = integers.stream().findFirst(); System.out.println(first); System.out.println(first.isPresent()); // 判斷是否不等於null,isPresent()相當於!=null的判斷 System.out.println(first.get()); //findFirst():返回流中的第一個元素,如果流為空,返回一個空的Optional List<Integer> lls = Collections.EMPTY_LIST; Optional<Integer> first1 = lls.stream().findFirst(); System.out.println(first1); System.out.println(first1.isPresent());
運行結果:
Optional[1]
true
1
Optional.empty
false
13、findAny():返回流中的任意一個元素即可,如果流為空,返回一個空的Optional.
// findAny():返回流中任意一個元素, List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6); Optional<Integer> any = list.stream().findAny(); // 並行流下每次返回的結果會不同 // Optional<Integer> any = list.stream().parallel().findAny(); System.out.println(any); System.out.println(any.isPresent()); System.out.println(any.get()); // findAny():返回流中任意一個元素,如果流為空,返回一個空的Optional List<Integer> list1 = Arrays.asList(); Optional<Integer> any1 = list1.stream().findAny(); System.out.println(any1); System.out.println(any1.isPresent());
運行結果:
Optional[1]
true
1
Optional.empty
false
以上就是Stream的13個終端操作,基本上可以覆蓋我們工作中的大部分操作,所以小伙伴朋友有必要掌握。
總結
Stream有以下特性及優點:
無存儲。Stream不是一種數據結構,它只是某種數據源的一個視圖,數據源可以是一個數組,Java容器或I/O channel等。
為函數式編程而生。對Stream的任何修改都不會修改背后的數據源,比如對Stream執行過濾操作並不會刪除被過濾的元素,而是會產生一個不包含被過濾元素的新Stream。
惰式執行。Stream上的操作並不會立即執行,只有等到用戶真正需要結果的時候才會執行。
可消費性。Stream只能被“消費”一次,一旦遍歷過就會失效,就像容器的迭代器那樣,想要再次遍歷必須重新生成。
對於無限數量的流,有些操作是可以在有限的時間完成的,比如limit(n) 或 findFirst(),這些操作可是實現"短路"(Short-circuiting),訪問到有限的元素后就可以返回。