這里寫目錄標題
- 一、Stream流概述
- 1.1、傳統寫法
- 1.2、Stream寫法
- 1.3、Stream流操作分類
- 二、Stream流獲取方式
- 2.1、根據Collection獲取
- 2.2、通過Stream的of方法
- 三、Stream常用方法介紹
- 3.1、forEach
- 3.2、count
- 3.3、filter
- 3.4、limit
- 3.5、skip
- 3.6、map
- 3.7、sorted
- 3.8、distinct
- 3.9、match
- 3.10、find
- 3.11、max和min
- 3.12、reduce方法
- 3.12.1、 map和reduce的組合
- 3.13、mapToInt
- 3.14、concat
- 3.15、綜合案例
- 4.1、結果收集到集合中
- 四、Stream結果手集
- 4.1、結果收集到集合中
- 4.2、結構收集到數組中
- 4.3、對流中數據做聚合操作
- 4.4、對流中數據做分組操作
- 4.5、對流中數據做分區操作
- 4.6、對流中數據做拼接
- 五、并行Stream流
- 5.1、串行的Stream流
- 5.2、并行流
- 5.2.1、獲取并行流
- 5.2.3、并行流操作
- 5.3、并行流和串行流對比
- 5.4、線程安全
一、Stream流概述
Java 中,Stream 是一個來自java.util.stream包的接口,用于對集合(如List、Set等)或數組等數據源進行操作的一種抽象層。
Stream流(和IO流沒有任何關系)主要是對數據進行加工處理的。Stream API能讓我們快速完成許多復雜的操作,如篩選、切片、映射、查找、去除重復,統計,匹配和歸約。
1.1、傳統寫法
現在有需求:對list中姓張,名字長度為3的信息打印:
public static void main(String[] args) {//定義一個List集合List<String> list = Arrays.asList("張三","張三豐","張無忌","李四","王五");//獲取姓張,名字長度為3的信息,添加到列表中List<String> list1=new ArrayList<>();for (String s : list) {if(s.startsWith("張")&&s.length()==3){list1.add(s);}}for (String s : list1) {System.out.println(s);}}
1.2、Stream寫法
public static void main(String[] args) {//定義一個List集合List<String> list = Arrays.asList("張三","張三豐","張無忌","李四","王五");list.stream().filter(s -> s.startsWith("張")).filter(s -> s.length()== 3).forEach(System.out::println);}
上面的SteamAPI代碼的含義:獲取流,過濾張,過濾長度,逐一打印。代碼相比于上面的案例更加的簡潔直觀。
1.3、Stream流操作分類
- 生成操作
通過數據源(集合、數組等)生成流。 - 中間操作
對流進行某種程度的過濾/映射,并返回一個新的流。 - 終結操作
執行某個終結操作,一個流只能有一個終結操作。
二、Stream流獲取方式
2.1、根據Collection獲取
java.util.Collection 接口中加入了default方法 stream,也就是說Collection接口下的所有的實現都可以通過steam方法來獲取Stream流。(java集合框架主要包括兩種類型的容器,一種是集合,存儲一個元素集合(Collection),另一種是圖(Map),存儲鍵/值對映射)。
public static void main(String[] args) {List<String> list=new ArrayList<>();Stream<String> stream=list.stream();Set<String> set=new HashSet<>();Stream<String> stream1=set.stream();Vector vector=new Vector();vector.stream();}
Map接口別沒有實現Collection接口,這時我們可以根據Map獲取對應的key value的集合。
public static void main(String[] args) {Map<String,Object> map=new HashMap<>();Stream<String> stream=map.keySet().stream();//keyStream<Object> stream1=map.values().stream();//valueStream<Map.Entry<String,Object>> stream2=map.entrySet().stream();//entry}
2.2、通過Stream的of方法
由于數組對象不可能添加默認方法,所有Stream接口中提供了靜態方法of操作到數組中的數據
public static void main(String[] args) {Stream<String> a1= Stream.of("a1","a2","a3");String[] arr1 = {"aa","bb","cc"};Stream<String> arr11 = Stream.of(arr1);Integer[] arr2 = {1,2,3,4};Stream<Integer> arr21 = Stream.of(arr2);arr21.forEach(System.out::println);// 注意:基本數據類型的數組是不行的int[] arr3 = {1,2,3,4};Stream.of(arr3).forEach(System.out::println);}
三、Stream常用方法介紹
Stream常用方法
方法名 | 方法作用 | 返回值類型 | 防范種類 |
---|---|---|---|
count | 統計個數 | long | 終結 |
forEach | 逐一處理 | void | 終結 |
filter | 過濾 | Stream | 函數拼接 |
limit | 取用前幾個 | Stream | 函數拼接 |
skip | 跳過前幾個 | Stream | 函數拼接 |
map | 映射 | Stream | 函數拼接 |
concat | 組合 | Stream | 函數拼接 |
注意: |
- 這里把常用的API分為“終結方法”和“非終結方法”
- “終結方法”:返回值類型不再是 Stream 類型的方法,不再支持鏈式調用。
- “非終結方法”:返回值類型仍然是 Stream 類型的方法,支持鏈式調用。
- Stream方法返回的是新的流。
- Stream不調用終結方法,中間的操作不會執行。
3.1、forEach
forEach用來遍歷流中的數據的。
void forEach(Consumer<? super T> action);
該方法接受一個Consumer接口,會將每一個流元素交給函數處理。
public static void main(String[] args) {Stream<String> a1=Stream.of("aa","bb","cc");a1.forEach(System.out::println);}
3.2、count
Stream流中的count方法用來統計其中的元素個數的。
long count();
該方法返回一個long值,代表元素的個數。
public static void main(String[] args) {long count = Stream.of("a1", "a2", "a3").count();System.out.println(count);}
3.3、filter
filter方法的作用是用來過濾數據的。返回符合條件的數據。
可以通過filter方法將一個流轉換成另一個子集流。
public static void main(String[] args) {Stream<String> stream =Stream.of("aa", "ab", "bc","a1","b2","c3").filter(s -> s.contains("a"));stream.forEach(System.out::println);}
該接口接收一個Predicate函數式接口參數作為篩選條件。
3.4、limit
limit方法可以對流進行截取處理,支取前n個數據,
Stream<T> limit(long maxSize);
參數式一個long類型的數值,如果集合當前長度大于參數就進行截取,否則不操作:
public static void main(String[] args) {Stream.of("a1", "a2", "a3","bb","cc","aa","dd").limit(3).forEach(System.out::println);}
3.5、skip
如果希望跳過前面幾個元素,可以使用skip方法獲取一個截取之后的新流:
Stream<T> skip(long n);
示例:
public static void main(String[] args) {Stream.of("a1","b2","c3","aa","bb","cc").skip(3).forEach(System.out::println);}
3.6、map
如果需要將流中的元素映射到另一個流中,可以使用map方法:
<R> Stream<R> map(Function<? super T, ? extends R> mapper);
該接口需要一個Function函數式接口參數,可以將當前流中的T類型數據轉換為另一種R類型的數據
public static void main(String[] args) {Stream.of("1","2","3","4","5")//.map(s -> Integer.parseInt(s)).map(Integer::parseInt).forEach(System.out::println);}
3.7、sorted
如果需要將數據排序,可以使用sorted方法:
Stream<T> sorted();
在使用的時候可以根據自然規則排序,也可以通過比較強來指定對應的排序規則
public static void main(String[] args) {Stream.of("1","2","7","9","3","4","6").map(Integer::parseInt).sorted((o1, o2) -> (o1 - o2)).forEach(System.out::println);}
3.8、distinct
如果要去掉重復數據,可以使用distinct方法
Stream<T> distinct();
Stream流中的distinct方法對于基本數據類型式可以直接去重的,但是對于自定義類型,我們需要重寫hashCode和equals方法來移除重復數據。
public static void main(String[] args) {Stream.of("1","2","4","5","2","3","4").sorted().distinct().forEach(System.out::println);System.out.println("----------------");Stream.of(new Person("張三",18),new Person("李四",18),new Person("王五",20),new Person("張三",18)).distinct().forEach(System.out::println);}
3.9、match
如果需要判斷數據是否匹配指定的條件,可以使用match相關的方法:
boolean anyMatch(Predicate<? super T> predicate); // 元素是否有任意一個滿足條件
boolean allMatch(Predicate<? super T> predicate); // 元素是否都滿足條件
boolean noneMatch(Predicate<? super T> predicate); // 元素是否都不滿足條件
使用:
public static void main(String[] args) {boolean b = Stream.of("1","2","3","4","5","7").map(Integer::parseInt)//.anyMatch(s-> s > 4);//.allMatch(s-> s > 4);.noneMatch(s-> s > 4);System.out.println(b);}
注:match是一個終結方法。
3.10、find
如果我們需要找到某些數據,可以使用find方法來實現
Optional<T> findFirst();Optional<T> findAny();
使用:
public static void main(String[] args) {Optional<String> first = Stream.of("a", "b", "c").findFirst();System.out.println(first.get());Optional<String> any = Stream.of("a", "b", "c","d").findAny();System.out.println(any.get());}
注:
3.11、max和min
如果我們想要獲取最大值和最小值,那么可以使用max和min方法
public static void main(String[] args) {Optional<Integer> max= Stream.of(1,2,3,4).max(Integer::compareTo);System.out.println(max.get());Optional<Integer> min= Stream.of(1,2,3,4).min(Integer::compareTo);System.out.println(min.get());}
3.12、reduce方法
如果需要將所有數據歸納得到一個數據,可以使用reduce方法:
public static void main(String[] args) {Integer sum = Stream.of(4,5,3,7)//identity默認值//第一次的時候會將默認值賦給x//之后每次將上一次的操作結果賦值給x y,就是每次從數據中獲取的元素.reduce(0, (x, y) -> {System.out.println("x="+x+",y="+y);return x + y;});System.out.println("sum = " + sum);// 獲取最大值Integer max = Stream.of(4,5,3,9).reduce(0,(x,y) ->{return x>y?x:y;});System.out.println("max = " + max);}
3.12.1、 map和reduce的組合
在實際開發中我們經常會將map和reduce一塊來使用:
public static void main(String[] args) {//1、求出所有年齡總和Integer sumAge= Stream.of(new Person("張三", 20),new Person("李四", 21),new Person("王五", 22),new Person("趙六", 23)).map(Person::getAge).reduce(0,Integer::sum);System.out.println(sumAge);//2、求出所有年齡最大值Integer maxAge= Stream.of(new Person("張三", 20),new Person("李四", 21),new Person("王五", 22),new Person("趙六", 23)).map(Person::getAge).reduce(Integer::max).get();System.out.println(maxAge);//3、統計字符 a 出現的次數Integer countA= Stream.of("a","b","c","d","e","a","a","a").map(ch -> ch.equals("a")?1:0).reduce(0,Integer::sum);System.out.println(countA);}
3.13、mapToInt
如果需要將Sream中的Integer類型轉換成int類型,可以使用mapToInt方法來實現
public static void main(String[] args) {//Integer 占用的內存比int多很多,在Stream流操作中會自動裝修和拆箱操作Integer arr[] ={1,2,3,4,6,7,8};Stream.of(arr).filter(x -> x > 0).forEach(System.out::println);//為了提高程序代碼效率,可以先將流中Integer數據轉為為int數據IntStream intStream = Stream.of(arr).mapToInt(Integer::intValue);intStream.forEach(System.out::println);}
3.14、concat
如果有兩個流,希望合并成為一個流,那么可以使用Stream接口防范concat
public static void main(String[] args) {Stream<String> steam1=Stream.of("a","b","c");Stream<String> steam2=Stream.of("x","y","z");//通過concat方法將兩個流合并成一個新的流Stream.concat(steam1,steam2).forEach(System.out::println);}
3.15、綜合案例
4.1、結果收集到集合中
public static void main(String[] args) {List<String> list1 = Arrays.asList("迪麗熱巴", "宋遠橋", "蘇星河", "老子","莊子", "孫子", "洪七公");List<String> list2 = Arrays.asList("古力娜扎", "張無忌", "張三豐", "趙麗穎","張二狗", "張天愛", "張三");Stream<String> stream1 = list1.stream().filter(s -> s.length() == 3).limit(3);Stream<String> stream2 =list2.stream().filter(s -> s.startsWith("張")).skip(2);Stream.concat(stream1,stream2)//.map(s -> new Person(s)).map(Person::new).forEach(System.out::println);}
四、Stream結果手集
4.1、結果收集到集合中
@Testpublic void test01(){//收集到list集合中List<String> list= Stream.of("a","b","c").collect(Collectors.toList());System.out.println(list);//收集到set集合中Set<String> set = Stream.of("aa","bb","cc","dd").collect(Collectors.toSet());System.out.println(set);//如果需要獲取的類型為具體實現ArrayList<String> arrayList = Stream.of("aaa","bbb","ccc")//.collect(Collectors.toCollection(() -> new ArrayList<>()));.collect(Collectors.toCollection(ArrayList::new));System.out.println(arrayList);}
4.2、結構收集到數組中
Stream中提供了toArray方法來將結果放到一個數組中,返回值類型是Object[]。
如果我們要指定返回的類型,那么可以使用另一個重載的toArray(IntFunction f)方法。
@Testpublic void test02(){//收集結果到數組中,數據類型是ObjectObject[] objects = Stream.of("aaa","bbb","ccc").toArray();System.out.println(Arrays.toString(objects));//收集結構到數組中,數據類型是StringString[] strings = Stream.of("aaa","bbb","ccc").toArray(String[]::new);System.out.println(Arrays.toString(strings));}
4.3、對流中數據做聚合操作
當我們使用Stream流處理數據后,可以根據某個屬性將數據分組
@Testpublic void test03(){//獲取年齡最大值List<Person> personList= Arrays.asList(new Person("張三",20),new Person("李四",25),new Person("王五",30),new Person("趙六",35));Optional<Person> maxAgePerson = personList.stream()//.collect(Collectors.maxBy(Comparator.comparingInt(Person::getAge)));.collect(Collectors.maxBy((p1,p2)->p1.getAge()-p2.getAge()));System.out.println("最大年齡: "+maxAgePerson.get());//獲取年齡最小值Optional<Person> minAgePerson = personList.stream().collect(Collectors.minBy((p1,p2)->p1.getAge()-p2.getAge()));System.out.println("最小年齡: "+minAgePerson.get());//求所有人的年齡之和Integer sumAge = personList.stream().collect(Collectors.summingInt(Person::getAge));System.out.println("年齡總和:" + sumAge);//求所有人的年齡平均值Double avgAge = personList.stream().collect(Collectors.averagingInt(Person::getAge));System.out.println("年齡的平均值:" + avgAge);//統計數量Long count = personList.stream().filter(p-> p.getAge() > 20).collect(Collectors.counting());System.out.println("滿足條件的記錄數:" + count);}
4.4、對流中數據做分組操作
當我們使用Stream流處理數據后,可以根據某個屬性將數據分組
public void test04(){List<Person> personList= Arrays.asList(new Person("張三", 18, 175), new Person("李四", 22, 177), new Person("張三", 14, 165), new Person("李四", 15, 166), new Person("張三", 19, 182));//根據姓名對數據分組Map<String,List<Person>> map1= personList.stream().collect(Collectors.groupingBy(Person::getName));map1.forEach((k,v)-> System.out.println("k=" + k +"\t"+ "v=" + v));System.out.println("-----------");Map<String, List<Person>> map2 = personList.stream().collect(Collectors.groupingBy(p -> p.getAge() >= 18 ? "成年" : "未成年"));map2.forEach((k,v)-> System.out.println("k=" + k +"\t"+ "v=" + v));}
多級分組
@Testpublic void test05(){List<Person> personList= Arrays.asList(new Person("張三", 16, 175), new Person("李四", 22, 177), new Person("張三", 14, 165), new Person("李四", 15, 166), new Person("張三", 19, 182));//先根據name分組,然后根據age(成年和未成年)分組Map<String,Map<Object,List<Person>>> map= personList.stream().collect(Collectors.groupingBy(Person::getName,Collectors.groupingBy(p-> p.getAge() >= 18 ? "成年" : "未成年")));map.forEach((k,v)->{System.out.println("k=" + k);v.forEach((kk,vv) -> System.out.println("\t"+"kk="+kk+"\tvv="+vv));});
4.5、對流中數據做分區操作
Collectors.partitioningBy會根據值是否為true,把集合中的數據分割為兩個列表,一個true列表,一個
false列表
@Testpublic void test06(){List<Person> personList= Arrays.asList(new Person("張三", 16, 175), new Person("李四", 22, 177), new Person("張三", 14, 165), new Person("李四", 15, 166), new Person("張三", 19, 182));Map<Boolean, List<Person>> map = personList.stream().collect(Collectors.partitioningBy(p -> p.getAge() > 18));map.forEach((k,v)-> System.out.println(k+"\t" + v));}
4.6、對流中數據做拼接
Collectors.joining會根據指定的連接符,將所有的元素連接成一個字符串
@Testpublic void test07(){List<Person> personList= Arrays.asList(new Person("張三", 18, 175), new Person("李四", 22, 177), new Person("張三", 14, 165), new Person("李四", 15, 166), new Person("張三", 19, 182));String s1 = personList.stream().map(Person::getName).collect(Collectors.joining());// 張三李四張三李四張三System.out.println(s1);String s2 = personList.stream().map(Person::getName).collect(Collectors.joining("_"));// 張三_李四_張三_李四_張三System.out.println(s2);String s3 = personList.stream().map(Person::getName).collect(Collectors.joining("_", "###", "$$$"));// ###張三_李四_張三_李四_張三$$$System.out.println(s3);}
五、并行Stream流
5.1、串行的Stream流
我們前面使用的Stream流都是串行,也就是在一個線程上面執行。
@Testpublic void test01(){long count = Stream.of(5,6,7,4,2,1,9).filter(s ->{System.out.println(Thread.currentThread().getName() + ":" + s);return s > 3;}).count();System.out.println(count);}
5.2、并行流
parallelStream其實就是一個并行執行的流,它通過默認的ForkJoinPool,可以提高多線程任務的速
度。
5.2.1、獲取并行流
@Testpublic void test02(){List<Integer> list=new ArrayList<>();//通過list接口直接獲取并行流Stream<Integer> stram=list.parallelStream();//將已有的串行流轉換為并行流Stream<Integer> parallel=Stream.of(1,2,3).parallel();}
5.2.3、并行流操作
@Testpublic void test03(){long count = Stream.of(5,6,7,4,2,1,9).parallel().filter(s ->{System.out.println(Thread.currentThread().getName() + ":" + s);return s > 3;}).count();System.out.println(count);}
5.3、并行流和串行流對比
我們通過for循環,串行Stream流,并行Stream流來對500000000億個數字求和。來看消耗時間
public class StresmTest24 {private static long times=500000000;private long start;@Beforepublic void before(){start=System.currentTimeMillis();}@Afterpublic void end(){long end=System.currentTimeMillis();System.out.println("消耗時間:"+(end - start));}@Testpublic void test01(){System.out.println("普通for循壞:");long res= 0;for (int i = 0;i<times;i++){res+=1;}}@Testpublic void test02(){System.out.println("串行流:serialStream");LongStream.rangeClosed(0,times).reduce(0,Long::sum);}@Testpublic void test03(){LongStream.rangeClosed(0,times).parallel().reduce(0,Long::sum);}}
5.4、線程安全
在多線程的處理下,肯定會出現數據安全問題。如下:
@Testpublic void test01(){List<Integer> list = new ArrayList<>();for (int i = 0; i < 1000; i++) {list.add(i);}System.out.println(list.size());List<Integer> listNew =new ArrayList<>();list.parallelStream().forEach(listNew::add);System.out.println(listNew.size());}
這個會拋出異常
java.lang.ArrayIndexOutOfBoundsException
針對這個問題,我們的解決方案有哪些呢?
- 加同步鎖
- 使用線程安全的容器
- 通過Stream中的toArray/collect操作
實現:
@Testpublic void test02(){List<Integer> listNew = new ArrayList<>();Object obj = new Object();IntStream.rangeClosed(1,1000).parallel().forEach(i->{synchronized (obj){listNew.add(i);}});System.out.println(listNew.size());}@Testpublic void test03(){Vector v = new Vector();Object obj = new Object();IntStream.rangeClosed(1,1000).parallel().forEach(i->{synchronized (obj){v.add(i);}});System.out.println(v.size());}@Testpublic void test04(){List<Integer> listNew = new ArrayList<>();// 將線程不安全的容器包裝為線程安全的容器List<Integer> synchronizedList = Collections.synchronizedList(listNew);Object obj = new Object();IntStream.rangeClosed(1,1000).parallel().forEach(i->{synchronizedList.add(i);});System.out.println(synchronizedList.size());}@Testpublic void test05(){List<Integer> listNew = new ArrayList<>();Object obj = new Object();List<Integer> list = IntStream.rangeClosed(1, 1000).parallel().boxed().collect(Collectors.toList());System.out.println(list.size());}