一文帶你掌握J(rèn)ava8強(qiáng)大的StreamAPI
Stream 概述
Stream API ( java.util.stream) 把真正的函數(shù)式編程風(fēng)格引入到Java中。這是目前為止對Java類庫最好的補(bǔ)充,因?yàn)镾tream API可以極大提供Java程序員的生產(chǎn)力,讓程序員寫出高效率、干凈、簡潔的代碼。
Stream 是 Java8 中處理集合的關(guān)鍵抽象概念,它可以指定你希望對集合進(jìn)行的操作,可以執(zhí)行非常復(fù)雜的查找、過濾和映射數(shù)據(jù)等操作。 使用Stream API 對集合數(shù)據(jù)進(jìn)行操作,就類似于使用 SQL 執(zhí)行的數(shù)據(jù)庫查詢。也可以使用 Stream API 來并行執(zhí)行操作。簡言之,Stream API提供了一種高效且易于使用的處理數(shù)據(jù)的方式。
實(shí)際開發(fā)中,項(xiàng)目中多數(shù)數(shù)據(jù)源都來自于Mysql,Oracle等。但隨著數(shù)據(jù)源豐富,有MongDB,Radis等,這些NoSQL的數(shù)據(jù)就需要Java層面去處理。
Stream 和 Collection 集合的區(qū)別:Collection 是一種靜態(tài)的內(nèi)存數(shù)據(jù)結(jié)構(gòu),而Stream 是有關(guān)計算的。前者是主要面向內(nèi)存,存儲在內(nèi)存中,后者主要是面向 CPU,通過 CPU 實(shí)現(xiàn)計算。
Stream 是數(shù)據(jù)渠道,用于操作數(shù)據(jù)源(集合、數(shù)組等)所生成的元素序列。
“集合講的是數(shù)據(jù),Stream講的是計算?!?/p>
注意:
①Stream 不會存儲元素。
②Stream 不會改變源對象。其會返回一個持有結(jié)果的新Stream。
③Stream 操作是延遲執(zhí)行的。其會等到需要結(jié)果的時候才執(zhí)行。
Stream 操作的三個步驟:
①Stream 實(shí)例化(創(chuàng)建):一個數(shù)據(jù)源(如:集合、數(shù)組),獲取一個流。
②中間操作:一個中間操作鏈,對數(shù)據(jù)源的數(shù)據(jù)進(jìn)行處理。
③終止操作(終端操作):一旦執(zhí)行終止操作,就執(zhí)行中間操作鏈,并產(chǎn)生結(jié)果。之后,不能再被使用(需要的話需要另一個Stream)。

Stream 實(shí)例化
1、方式一:通過集合
Java8 中的 Collection 接口被擴(kuò)展,提供了兩個獲取流的方法:
import java.util.ArrayList;
import java.util.stream.Stream;
public class StreamAPITest {
public static void main(String[] args) {
List<String> arrayList = new ArrayList<>();
arrayList.add("aa");
arrayList.add("哈哈");
arrayList.add("99");
//返回一個順序流,即"aa"->"哈哈"->"99"
Stream<String> stream1 = arrayList.stream();
//返回一個并行流
Stream<String> stream2 = arrayList.parallelStream();
}
}
2、方式二:通過數(shù)組
Java8 中的 Arrays 的靜態(tài)方法 stream() 可以獲取數(shù)組流:
import java.util.Arrays;
import java.util.stream.Stream;
public class StreamAPITest {
public static void main(String[] args) {
Double[] doubles = {1.1, 2.0, 4.3, 9.9};
Stream<Double> stream = Arrays.stream(doubles);
}
}

3、方式三:通過Stream的of()
調(diào)用Stream類靜態(tài)方法 of(),通過顯示值創(chuàng)建一個流,其可接收任意數(shù)量的參數(shù):
import java.util.stream.Stream;
public class StreamAPITest {
public static void main(String[] args) {
Double[] doubles = {1.1, 2.0, 4.3, 9.9};
Stream<Double> doubles1 = Stream.of(doubles);
Stream<? extends Number> stream = Stream.of(1, 2, 3, 9.9);
}
}
4、方式四:創(chuàng)建無限流
可以使用靜態(tài)方法 Stream.iterate() 和 Stream.generate() 創(chuàng)建無限流:
import java.util.stream.Stream;
public class StreamAPITest {
public static void main(String[] args) {
// 迭代
// public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f)
Stream<Integer> stream = Stream.iterate(0, x -> x + 2);
stream.limit(10).forEach(System.out::println);
// 生成
// public static<T> Stream<T> generate(Supplier<T> s)
Stream<Double> stream1 = Stream.generate(Math::random);
stream1.limit(10).forEach(System.out::println);
}
}
Stream 中間操作
多個中間操作可以連接起來形成一個流水線,除非流水線上觸發(fā)終止操作,否則中間操作不會執(zhí)行任何的處理。而在終止操作時一次性全部處理,稱為“惰性求值”。
1、篩選與切片

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
/**
* @Author: Yeman
* @Date: 2021-10-05-17:25
* @Description:
*/
public class StreamAPITest {
public static void main(String[] args) {
List<String> arrayList = Arrays.asList("aa","bb","cc","aa");
Stream<String> stream = arrayList.stream();
stream.filter(e -> !e.equals("aa")).forEach(System.out :: println); //bb cc
System.out.println("==========");
arrayList.stream().limit(2).forEach(System.out :: println); //aa bb
System.out.println("==========");
arrayList.stream().skip(2).forEach(System.out :: println); //cc aa
System.out.println("==========");
arrayList.stream().distinct().forEach(System.out :: println); //aa bb cc
}
}
2、映射

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
/**
* @Author: Yeman
* @Date: 2021-10-05-17:25
* @Description:
*/
public class StreamAPITest {
public static void main(String[] args) {
List<String> arrayList = Arrays.asList("aa","bb","cc","aa");
Stream<String> stream = arrayList.stream();
stream.map(x -> x.toUpperCase()).forEach(System.out :: println); //AA BB CC AA
System.out.println("====================");
arrayList.stream().map(StreamAPITest::fromStringToStream).forEach(System.out :: println); //類似于add()
arrayList.stream().flatMap(StreamAPITest::fromStringToStream).forEach(System.out :: println); //類似于addAll()
}
public static Stream<Character> fromStringToStream(String str){
ArrayList<Character> arrayList = new ArrayList<>();
for (Character c : str.toCharArray()){
arrayList.add(c);
}
return arrayList.stream();
}
}
3、排序

import java.util.Arrays;
import java.util.List;
/**
* @Author: Yeman
* @Date: 2021-10-05-17:25
* @Description:
*/
public class StreamAPITest {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(2, -9, 0, 22, 6, -1);
list.stream().sorted().forEach(System.out::println);
System.out.println("===============");
list.stream().sorted((e1,e2) -> -Integer.compare(e1,e2)).forEach(System.out :: println);
}
}
Stream 終止操作
終端操作會從流的流水線生成結(jié)果。其結(jié)果可以是任何不是流的值,例如:List、Integer,甚至是 void 。流進(jìn)行了終止操作后,不能再次使用。
1、匹配與查找


import java.util.Arrays;
import java.util.List;
import java.util.Optional;
/**
* @Author: Yeman
* @Date: 2021-10-05-17:25
* @Description:
*/
public class StreamAPITest {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(2, -9, 0, 22, 6, -1);
boolean allMatch = list.stream().allMatch(e -> e > 0);
System.out.println(allMatch);
boolean anyMatch = list.stream().anyMatch(e -> e > 0);
System.out.println(anyMatch);
boolean noneMatch = list.stream().noneMatch(e -> e > 100);
System.out.println(noneMatch);
System.out.println("==========================");
Optional<Integer> first = list.stream().sorted().findFirst();
System.out.println(first);
Optional<Integer> any = list.parallelStream().findAny();
System.out.println(any);
System.out.println("==========================");
long count = list.stream().filter(e -> e > 0).count();
System.out.println(count);
System.out.println("==========================");
Optional<Integer> max = list.stream().max(Integer :: compare);
System.out.println(max);
Optional<Integer> min = list.stream().min((e1, e2) -> Integer.compare(e1, e2));
System.out.println(min);
System.out.println("==========================");
list.stream().forEach(System.out :: println);
}
}
2、歸約
map 和 reduce 的連接通常稱為 map-reduce 模式,因 Google 用它來進(jìn)行網(wǎng)絡(luò)搜索而出名。

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
/**
* @Author: Yeman
* @Date: 2021-10-05-17:25
* @Description:
*/
public class StreamAPITest {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(2, -9, 0, 22, 6, -1);
Integer reduce1 = list.stream().reduce(0, Integer::sum);
Integer reduce11 = list.stream().reduce(0, (e1,e2) -> e1 + e2);
System.out.println(reduce1);
System.out.println(reduce11);
Optional<Integer> reduce2 = list.stream().reduce(Integer::sum);
System.out.println(reduce2);
}
}
3、收集

Collector 接口中方法的實(shí)現(xiàn)決定了如何對流執(zhí)行收集的操作(如收集到 List、Set、
Map)。另外, Collectors 實(shí)用類提供了很多靜態(tài)方法,可以方便地創(chuàng)建常見收集器實(shí)例,具體方法與實(shí)例如下表:


import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* @Author: Yeman
* @Date: 2021-10-05-17:25
* @Description:
*/
public class StreamAPITest {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(2, -9, 0, 22, 6, -1);
List<Integer> collect = list.stream().filter(e -> e > 0).collect(Collectors.toList());
collect.forEach(System.out :: println); //2 22 6
}
}
到此這篇關(guān)于一文帶你掌握J(rèn)ava8強(qiáng)大的StreamAPI 的文章就介紹到這了,更多相關(guān)Java Stream內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java中為什么要實(shí)現(xiàn)Serializable序列化
在Java編程中,Serializable序列化是一個常見的概念,它允許對象在網(wǎng)絡(luò)上傳輸或持久化到磁盤上,本文將深入探討為什么在Java中要實(shí)現(xiàn)Serializable序列化,并通過示例代碼來解釋其重要性2023-10-10
Java實(shí)戰(zhàn)之實(shí)現(xiàn)用戶登錄
這篇文章主要介紹了Java實(shí)戰(zhàn)之實(shí)現(xiàn)用戶登錄,文中有非常詳細(xì)的代碼示例,對正在學(xué)習(xí)java的小伙伴們有非常好的幫助,需要的朋友可以參考下2021-04-04
java實(shí)現(xiàn)后臺數(shù)據(jù)顯示在前端
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)后臺數(shù)據(jù)顯示在前端,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-02-02

