本篇文章給大家?guī)砹岁P于java的相關知識,其中主要介紹了關于Stream詳細用法的相關問題,版本新增的Stream,配合同版本出現(xiàn)的Lambda ,給我們操作集合(Collection)提供了極大的便利,下面一起來看一下,希望對大家有幫助。
程序員必備接口測試調試工具:立即使用
Apipost = Postman + Swagger + Mock + Jmeter
Api設計、調試、文檔、自動化測試工具
后端、前端、測試,同時在線協(xié)作,內容實時同步
推薦學習:《java視頻教程》
一、概述
Java 8 是一個非常成功的版本,這個版本新增的Stream,配合同版本出現(xiàn)的Lambda ,給我們操作集合(Collection)提供了極大的便利。Stream流是JDK8新增的成員,允許以聲明性方式處理數(shù)據(jù)集合,可以把Stream流看作是遍歷數(shù)據(jù)集合的一個高級迭代器。Stream 是 Java8 中處理集合的關鍵抽象概念,它可以指定你希望對集合進行的操作,可以執(zhí)行非常復雜的查找/篩選/過濾、排序、聚合和映射數(shù)據(jù)等操作。使用Stream API 對集合數(shù)據(jù)進行操作,就類似于使用 SQL 執(zhí)行的數(shù)據(jù)庫查詢。也可以使用 Stream API 來并行執(zhí)行操作。簡而言之,Stream API 提供了一種高效且易于使用的處理數(shù)據(jù)的方式。
1、使用流的好處
代碼以聲明性方式書寫,說明想要完成什么,而不是說明如何完成一個操作。
可以把幾個基礎操作連接起來,來表達復雜的數(shù)據(jù)處理的流水線,同時保持代碼清晰可讀。
2、流是什么?
從支持數(shù)據(jù)處理操作的源生成元素序列.數(shù)據(jù)源可以是集合,數(shù)組或IO資源。
從操作角度來看,流與集合是不同的. 流不存儲數(shù)據(jù)值; 流的目的是處理數(shù)據(jù),它是關于算法與計算的。
如果把集合作為流的數(shù)據(jù)源,創(chuàng)建流時不會導致數(shù)據(jù)流動; 如果流的終止操作需要值時,流會從集合中獲取值; 流只使用一次。
流中心思想是延遲計算,流直到需要時才計算值。
Stream可以由數(shù)組或集合創(chuàng)建,對流的操作分為兩種:
中間操作,每次返回一個新的流,可以有多個。
終端操作,每個流只能進行一次終端操作,終端操作結束后流無法再次使用。終端操作會產(chǎn)生一個新的集合或值。
特性:
不是數(shù)據(jù)結構,不會保存數(shù)據(jù)。
不會修改原來的數(shù)據(jù)源,它會將操作后的數(shù)據(jù)保存到另外一個對象中。(保留意見:畢竟peek方法可以修改流中元素)
惰性求值,流在中間處理過程中,只是對操作進行了記錄,并不會立即執(zhí)行,需要等到執(zhí)行終止操作的時候才會進行實際的計算。
二、分類
無狀態(tài):指元素的處理不受之前元素的影響;
有狀態(tài):指該操作只有拿到所有元素之后才能繼續(xù)下去。
非短路操作:指必須處理所有元素才能得到最終結果;
短路操作:指遇到某些符合條件的元素就可以得到最終結果,如 A || B,只要A為true,則無需判斷B的結果。
三、Stream的創(chuàng)建
Stream可以通過集合數(shù)組創(chuàng)建。
1、通過 java.util.Collection.stream() 方法用集合創(chuàng)建流
Listlist = Arrays.asList("a", "b", "c");// 創(chuàng)建一個順序流 Stream stream = list.stream();// 創(chuàng)建一個并行流 Stream parallelStream = list.parallelStream();
2、使用 java.util.Arrays.stream(T[]array)方法用數(shù)組創(chuàng)建流
int[] array={1,3,5,6,8};IntStream stream = Arrays.stream(array);
3、使用 Stream的靜態(tài)方法:of()、iterate()、generate()
Streamstream = Stream.of(1, 2, 3, 4, 5, 6); Stream stream2 = Stream.iterate(0, (x) -> x + 3).limit(4);stream2.forEach(System.out::println); Stream stream3 = Stream.generate(Math::random).limit(3);stream3.forEach(System.out::println);
輸出結果:
0 3 6 90.67961569092719940.19143142088542830.8116932592396652
stream和 parallelStream的簡單區(qū)分:stream是順序流,由主線程按順序對流執(zhí)行操作,而 parallelStream是并行流,內部以多線程并行執(zhí)行的方式對流進行操作,但前提是流中的數(shù)據(jù)處理沒有順序要求。例如篩選集合中的奇數(shù),兩者的處理不同之處:
如果流中的數(shù)據(jù)量足夠大,并行流可以加快處速度。
除了直接創(chuàng)建并行流,還可以通過 parallel()把順序流轉換成并行流:
OptionalfindFirst = list.stream().parallel().filter(x->x>6).findFirst();
四、Stream API簡介
先貼上幾個案例,水平高超的同學可以挑戰(zhàn)一下:從員工集合中篩選出salary大于8000的員工,并放置到新的集合里。統(tǒng)計員工的最高薪資、平均薪資、薪資之和。將員工按薪資從高到低排序,同樣薪資者年齡小者在前。將員工按性別分類,將員工按性別和地區(qū)分類,將員工按薪資是否高于8000分為兩部分。用傳統(tǒng)的迭代處理也不是很難,但代碼就顯得冗余了,跟Stream相比高下立判。
前提:員工類
static ListpersonList = new ArrayList ();private static void initPerson() { personList.add(new Person("張三", 8, 3000)); personList.add(new Person("李四", 18, 5000)); personList.add(new Person("王五", 28, 7000)); personList.add(new Person("孫六", 38, 9000));}
1、遍歷/匹配(foreach/find/match)
Stream也是支持類似集合的遍歷和匹配元素的,只是 Stream中的元素是以 Optional類型存在的。Stream的遍歷、匹配非常簡單。
// import已省略,請自行添加,后面代碼亦是 public class StreamTest { public static void main(String[] args) { Listlist = Arrays.asList(7, 6, 9, 3, 8, 2, 1); // 遍歷輸出符合條件的元素 list.stream().filter(x -> x > 6).forEach(System.out::println); // 匹配第一個 Optional findFirst = list.stream().filter(x -> x > 6).findFirst(); // 匹配任意(適用于并行流) Optional findAny = list.parallelStream().filter(x -> x > 6).findAny(); // 是否包含符合特定條件的元素 boolean anyMatch = list.stream().anyMatch(x -> x < 6); System.out.println("匹配第一個值:" + findFirst.get()); System.out.println("匹配任意一個值:" + findAny.get()); System.out.println("是否存在大于6的值:" + anyMatch); }}
2、按條件匹配filter
(1)篩選員工中已滿18周歲的人,并形成新的集合
/** * 篩選員工中已滿18周歲的人,并形成新的集合 * @思路 * Listlist = new ArrayList (); * for(Person person : personList) { * if(person.getAge() >= 18) { * list.add(person); * } * } */ private static void filter01() { initPerson(); List collect = personList.stream().filter(x -> x.getAge()>=18).collect(Collectors.toList()); System.out.println(collect);}
(2)自定義條件匹配
3、聚合max、min、count
(1)獲取String集合中最長的元素
/** * 獲取String集合中最長的元素 * @思路 * Listlist = Arrays.asList("zhangsan", "lisi", "wangwu", "sunliu"); * String max = ""; * int length = 0; * int tempLength = 0; * for(String str : list) { * tempLength = str.length(); * if(tempLength > length) { * length = str.length(); * max = str; * } * } * @return zhangsan */ private static void test02() { List list = Arrays.asList("zhangsan", "lisi", "wangwu", "sunliu"); Comparator super String> comparator = Comparator.comparing(String::length); Optional max = list.stream().max(comparator); System.out.println(max);}
(2)獲取Integer集合中的最大值
//獲取Integer集合中的最大值 private static void test05() { Listlist = Arrays.asList(1, 17, 27, 7); Optional max = list.stream().max(Integer::compareTo); // 自定義排序 Optional max2 = list.stream().max(new Comparator () { @Override public int compare(Integer o1, Integer o2) { return o1.compareTo(o2); } }); System.out.println(max2);}
//獲取員工中年齡最大的人 private static void test06() { initPerson(); Comparator super Person> comparator = Comparator.comparingInt(Person::getAge); Optionalmax = personList.stream().max(comparator); System.out.println(max);}
(3)獲取員工中年齡最大的人
(4)計算integer集合中大于10的元素的個數(shù)
4、map與flatMap
map:接收一個函數(shù)作為參數(shù),該函數(shù)會被應用到每個元素上,并將其映射成一個新的元素。
flatMap:接收一個函數(shù)作為參數(shù),將流中的每個值都換成另一個流,然后把所有流連接成一個流。
(1)字符串大寫
(2)整數(shù)數(shù)組每個元素+3
/** * 整數(shù)數(shù)組每個元素+3 * @思路 * Listlist = Arrays.asList(1, 17, 27, 7); List list2 = new ArrayList (); for(Integer num : list) { list2.add(num + 3); } @return [4, 20, 30, 10] */ private static void test09() { List list = Arrays.asList(1, 17, 27, 7); List collect = list.stream().map(x -> x + 3).collect(Collectors.toList()); System.out.println(collect);}
(3)公司效益好,每人漲2000
/** * 公司效益好,每人漲2000 * */ private static void test10() { initPerson(); Listcollect = personList.stream().map(x -> { x.setAge(x.getSalary()+2000); return x; }).collect(Collectors.toList()); System.out.println(collect);}
(4)將兩個字符數(shù)組合并成一個新的字符數(shù)組
/** * 將兩個字符數(shù)組合并成一個新的字符數(shù)組 * */ private static void test11() { String[] arr = {"z, h, a, n, g", "s, a, n"}; Listlist = Arrays.asList(arr); System.out.println(list); List collect = list.stream().flatMap(x -> { String[] array = x.split(","); Stream stream = Arrays.stream(array); return stream; }).collect(Collectors.toList()); System.out.println(collect);}
(5)將兩個字符數(shù)組合并成一個新的字符數(shù)組
/** * 將兩個字符數(shù)組合并成一個新的字符數(shù)組 * @return [z, h, a, n, g, s, a, n] */ private static void test11() { String[] arr = {"z, h, a, n, g", "s, a, n"}; Listlist = Arrays.asList(arr); List collect = list.stream().flatMap(x -> { String[] array = x.split(","); Stream stream = Arrays.stream(array); return stream; }).collect(Collectors.toList()); System.out.println(collect);}
5、規(guī)約reduce
歸約,也稱縮減,顧名思義,是把一個流縮減成一個值,能實現(xiàn)對集合求和、求乘積和求最值操作。
(1)求Integer集合的元素之和、乘積和最大值
/** * 求Integer集合的元素之和、乘積和最大值 * */ private static void test13() { Listlist = Arrays.asList(1, 2, 3, 4); //求和 Optional reduce = list.stream().reduce((x,y) -> x+ y); System.out.println("求和:"+reduce); //求積 Optional reduce2 = list.stream().reduce((x,y) -> x * y); System.out.println("求積:"+reduce2); //求最大值 Optional reduce3 = list.stream().reduce((x,y) -> x>y?x:y); System.out.println("求最大值:"+reduce3);}
(2)求所有員工的工資之和和最高工資
/* * 求所有員工的工資之和和最高工資 */ private static void test14() { initPerson(); Optionalreduce = personList.stream().map(Person :: getSalary).reduce(Integer::sum); Optional reduce2 = personList.stream().map(Person :: getSalary).reduce(Integer::max); System.out.println("工資之和:"+reduce); System.out.println("最高工資:"+reduce2);}
6、收集(toList、toSet、toMap)
取出大于18歲的員工轉為map
/** * 取出大于18歲的員工轉為map * */ private static void test15() { initPerson(); Mapcollect = personList.stream().filter(x -> x.getAge() > 18).collect(Collectors.toMap(Person::getName, y -> y)); System.out.println(collect);}
7、collect
Collectors提供了一系列用于數(shù)據(jù)統(tǒng)計的靜態(tài)方法:
計數(shù): count
平均值: averagingInt、 averagingLong、 averagingDouble
最值: maxBy、 minBy
求和: summingInt、 summingLong、 summingDouble
統(tǒng)計以上所有: summarizingInt、 summarizingLong、 summarizingDouble
/** * 統(tǒng)計員工人數(shù)、平均工資、工資總額、最高工資 */ private static void test01(){ //統(tǒng)計員工人數(shù) Long count = personList.stream().collect(Collectors.counting()); //求平均工資 Double average = personList.stream().collect(Collectors.averagingDouble(Person::getSalary)); //求最高工資 Optionalmax = personList.stream().map(Person::getSalary).collect(Collectors.maxBy(Integer::compare)); //求工資之和 Integer sum = personList.stream().collect(Collectors.summingInt(Person::getSalary)); //一次性統(tǒng)計所有信息 DoubleSummaryStatistics collect = personList.stream().collect(Collectors.summarizingDouble(Person::getSalary)); System.out.println("統(tǒng)計員工人數(shù):"+count); System.out.println("求平均工資:"+average); System.out.println("求最高工資:"+max); System.out.println("求工資之和:"+sum); System.out.println("一次性統(tǒng)計所有信息:"+collect);}
8、分組(partitioningBy/groupingBy)
分區(qū):將stream按條件分為兩個 Map,比如員工按薪資是否高于8000分為兩部分。
分組:將集合分為多個Map,比如員工按性別分組。有單級分組和多級分組。
將員工按薪資是否高于8000分為兩部分;將員工按性別和地區(qū)分組
public class StreamTest { public static void main(String[] args) { personList.add(new Person("zhangsan",25, 3000, "male", "tieling")); personList.add(new Person("lisi",27, 5000, "male", "tieling")); personList.add(new Person("wangwu",29, 7000, "female", "tieling")); personList.add(new Person("sunliu",26, 3000, "female", "dalian")); personList.add(new Person("yinqi",27, 5000, "male", "dalian")); personList.add(new Person("guba",21, 7000, "female", "dalian")); // 將員工按薪資是否高于8000分組 Map> part = personList.stream().collect(Collectors.partitioningBy(x -> x.getSalary() > 8000)); // 將員工按性別分組 Map > group = personList.stream().collect(Collectors.groupingBy(Person::getSex)); // 將員工先按性別分組,再按地區(qū)分組 Map >> group2 = personList.stream().collect(Collectors.groupingBy(Person::getSex, Collectors.groupingBy(Person::getArea))); System.out.println("員工按薪資是否大于8000分組情況:" + part); System.out.println("員工按性別分組情況:" + group); System.out.println("員工按性別、地區(qū):" + group2); }}
9、連接joining
joining可以將stream中的元素用特定的連接符(沒有的話,則直接連接)連接成一個字符串。
10、排序sorted
將員工按工資由高到低(工資一樣則按年齡由大到?。┡判?/p>
private static void test04(){ // 按工資升序排序(自然排序) ListnewList = personList.stream().sorted(Comparator.comparing(Person::getSalary)).map(Person::getName) .collect(Collectors.toList()); // 按工資倒序排序 List newList2 = personList.stream().sorted(Comparator.comparing(Person::getSalary).reversed()) .map(Person::getName).collect(Collectors.toList()); // 先按工資再按年齡升序排序 List newList3 = personList.stream() .sorted(Comparator.comparing(Person::getSalary).thenComparing(Person::getAge)).map(Person::getName) .collect(Collectors.toList()); // 先按工資再按年齡自定義排序(降序) List newList4 = personList.stream().sorted((p1, p2) -> { if (p1.getSalary() == p2.getSalary()) { return p2.getAge() - p1.getAge(); } else { return p2.getSalary() - p1.getSalary(); } }).map(Person::getName).collect(Collectors.toList()); System.out.println("按工資升序排序:" + newList); System.out.println("按工資降序排序:" + newList2); System.out.println("先按工資再按年齡升序排序:" + newList3); System.out.println("先按工資再按年齡自定義降序排序:" + newList4);}
11、提取/組合
流也可以進行合并、去重、限制、跳過等操作。
private static void test05(){ String[] arr1 = { "a", "b", "c", "d" }; String[] arr2 = { "d", "e", "f", "g" }; Streamstream1 = Stream.of(arr1); Stream stream2 = Stream.of(arr2); // concat:合并兩個流 distinct:去重 List newList = Stream.concat(stream1, stream2).distinct().collect(Collectors.toList()); // limit:限制從流中獲得前n個數(shù)據(jù) List collect = Stream.iterate(1, x -> x + 2).limit(10).collect(Collectors.toList()); // skip:跳過前n個數(shù)據(jù) List collect2 = Stream.iterate(1, x -> x + 2).skip(1).limit(5).collect(Collectors.toList()); System.out.println("流合并:" + newList); System.out.println("limit:" + collect); System.out.println("skip:" + collect2);}
12、讀取文件的流操作
13、計算兩個list中的差集
//計算兩個list中的差集 Listreduce1 = allList.stream().filter(item -> !wList.contains(item)).collect(Collectors.toList());
推薦學習:《java視頻教程》