使用Stream API優(yōu)化代碼
作者:何甜甜在嗎
juejin.im/post/5d8226d4e51d453c135c5b9a
Java8的新特性主要是Lambda表達(dá)式和流,當(dāng)流和Lambda表達(dá)式結(jié)合起來一起使用時,因為流申明式處理數(shù)據(jù)集合的特點,可以讓代碼變得簡潔易讀
放大招,流如何簡化代碼
如果有一個需求,需要對數(shù)據(jù)庫查詢到的菜肴進行一個處理:
篩選出卡路里小于400的菜肴
對篩選出的菜肴進行一個排序
獲取排序后菜肴的名字
菜肴:Dish.java
public?class?Dish?{
????private?String?name;
????private?boolean?vegetarian;
????private?int?calories;
????private?Type?type;
????//?getter?and?setter
}
Java8以前的實現(xiàn)方式
private?List<String>?beforeJava7(List?dishList)?{
????????List?lowCaloricDishes?=?new?ArrayList<>();
????????//1.篩選出卡路里小于400的菜肴
????????for?(Dish?dish?:?dishList)?{
????????????if?(dish.getCalories()?400)?{
????????????????lowCaloricDishes.add(dish);
????????????}
????????}
????????//2.對篩選出的菜肴進行排序
????????Collections.sort(lowCaloricDishes,?new?Comparator()?{
????????????@Override
????????????public?int?compare(Dish?o1,?Dish?o2)?{
????????????????return?Integer.compare(o1.getCalories(),?o2.getCalories());
????????????}
????????});
????????//3.獲取排序后菜肴的名字
????????List<String>?lowCaloricDishesName?=?new?ArrayList<>();
????????for?(Dish?d?:?lowCaloricDishes)?{
????????????lowCaloricDishesName.add(d.getName());
????????}
????????return?lowCaloricDishesName;
????}
Java8之后的實現(xiàn)方式
?private?List?afterJava8(List?dishList)?{
????????return?dishList.stream()
????????????????.filter(d?->?d.getCalories()?400)??//篩選出卡路里小于400的菜肴
????????????????.sorted(comparing(Dish::getCalories))??//根據(jù)卡路里進行排序
????????????????.map(Dish::getName)??//提取菜肴名稱
????????????????.collect(Collectors.toList());?//轉(zhuǎn)換為List
????}
不拖泥帶水,一氣呵成,原來需要寫24代碼實現(xiàn)的功能現(xiàn)在只需5行就可以完成了

高高興興寫完需求這時候又有新需求了,新需求如下:
對數(shù)據(jù)庫查詢到的菜肴根據(jù)菜肴種類進行分類,返回一個Map>的結(jié)果
這要是放在jdk8之前肯定會頭皮發(fā)麻
Java8以前的實現(xiàn)方式
private?static?Map<Type,?List>?beforeJdk8(List?dishList)?{
????Map<Type,?List>?result?=?new?HashMap<>();
????for?(Dish?dish?:?dishList)?{
????????//不存在則初始化
????????if?(result.get(dish.getType())==null)?{
????????????List?dishes?=?new?ArrayList<>();
????????????dishes.add(dish);
????????????result.put(dish.getType(),?dishes);
????????}?else?{
????????????//存在則追加
????????????result.get(dish.getType()).add(dish);
????????}
????}
????return?result;
}
還好jdk8有Stream,再也不用擔(dān)心復(fù)雜集合處理需求
Java8以后的實現(xiàn)方式
private?static?MapList>?afterJdk8(List?dishList)?{
????return?dishList.stream().collect(groupingBy(Dish::getType));
}
又是一行代碼解決了需求,忍不住大喊Stream API牛批 看到流的強大功能了吧,接下來將詳細(xì)介紹流

什么是流
流是從支持?jǐn)?shù)據(jù)處理操作的源生成的元素序列,源可以是數(shù)組、文件、集合、函數(shù)。流不是集合元素,它不是數(shù)據(jù)結(jié)構(gòu)并不保存數(shù)據(jù),它的主要目的在于計算
如何生成流
生成流的方式主要有五種
1.通過集合生成,應(yīng)用中最常用的一種
List<Integer>?integerList?=?Arrays.asList(1,?2,?3,?4,?5);
Stream<Integer>?stream?=?integerList.stream();
通過集合的stream方法生成流
2.通過數(shù)組生成
int[]?intArr?=?new?int[]{1,?2,?3,?4,?5};
IntStream?stream?=?Arrays.stream(intArr);
通過Arrays.stream方法生成流,并且該方法生成的流是數(shù)值流【即IntStream】而不是Stream。補充一點使用數(shù)值流可以避免計算過程中拆箱裝箱,提高性能。
Stream API提供了mapToInt、mapToDouble、mapToLong三種方式將對象流【即Stream
3.通過值生成
Stream<Integer>?stream?=?Stream.of(1,?2,?3,?4,?5);
通過Stream的of方法生成流,通過Stream的empty方法可以生成一個空流
4.通過文件生成
Stream?lines?=?Files.lines(Paths.get("data.txt"),?Charset.defaultCharset())
通過Files.line方法得到一個流,并且得到的每個流是給定文件中的一行
5.通過函數(shù)生成 提供了iterate和generate兩個靜態(tài)方法從函數(shù)中生成流
iterator
Stream?stream?=?Stream.iterate(0,?n?->?n?+?2).limit(5);
iterate方法接受兩個參數(shù),第一個為初始化值,第二個為進行的函數(shù)操作,因為iterator生成的流為無限流,通過limit方法對流進行了截斷,只生成5個偶數(shù)
generator
Stream?stream?=?Stream.generate(Math::random).limit(5);
generate方法接受一個參數(shù),方法參數(shù)類型為Supplier
流的操作類型
流的操作類型主要分為兩種
1.中間操作
一個流可以后面跟隨零個或多個中間操作。其目的主要是打開流,做出某種程度的數(shù)據(jù)映射/過濾,然后返回一個新的流,交給下一個操作使用。這類操作都是惰性化的,僅僅調(diào)用到這類方法,并沒有真正開始流的遍歷,真正的遍歷需等到終端操作時,常見的中間操作有下面即將介紹的filter、map等
2.終端操作
一個流有且只能有一個終端操作,當(dāng)這個操作執(zhí)行后,流就被關(guān)閉了,無法再被操作,因此一個流只能被遍歷一次,若想在遍歷需要通過源數(shù)據(jù)在生成流。終端操作的執(zhí)行,才會真正開始流的遍歷。如下面即將介紹的count、collect等
流使用
流的使用將分為終端操作和中間操作進行介紹
中間操作
filter篩選
?List<Integer>?integerList?=?Arrays.asList(1,?1,?2,?3,?4,?5);
?Stream<Integer>?stream?=?integerList.stream().filter(i?->?i?>?3);
通過使用filter方法進行條件篩選,filter的方法參數(shù)為一個條件
distinct去除重復(fù)元素
List<Integer>?integerList?=?Arrays.asList(1,?1,?2,?3,?4,?5);
Stream<Integer>?stream?=?integerList.stream().distinct();
通過distinct方法快速去除重復(fù)的元素
limit返回指定流個數(shù)
?List<Integer>?integerList?=?Arrays.asList(1,?1,?2,?3,?4,?5);
?Stream<Integer>?stream?=?integerList.stream().limit(3);
通過limit方法指定返回流的個數(shù),limit的參數(shù)值必須>=0,否則將會拋出異常
skip跳過流中的元素
?List<Integer>?integerList?=?Arrays.asList(1,?1,?2,?3,?4,?5);
?Stream<Integer>?stream?=?integerList.stream().skip(2);
通過skip方法跳過流中的元素,上述例子跳過前兩個元素,所以打印結(jié)果為2,3,4,5,skip的參數(shù)值必須>=0,否則將會拋出異常
map流映射
所謂流映射就是將接受的元素映射成另外一個元素
List<String>?stringList?=?Arrays.asList("Java?8",?"Lambdas",??"In",?"Action");
Stream?stream?=?stringList.stream().map(String::length);
通過map方法可以完成映射,該例子完成中String -> Integer的映射,之前上面的例子通過map方法完成了Dish->String的映射
flatMap流轉(zhuǎn)換
將一個流中的每個值都轉(zhuǎn)換為另一個流
List?wordList?=?Arrays.asList("Hello",?"World");
List?strList?=?wordList.stream()
????????.map(w?->?w.split("?"))
????????.flatMap(Arrays::stream)
????????.distinct()
????????.collect(Collectors.toList());
map(w -> w.split(" "))的返回值為Stream,我們想獲取Stream,可以通過flatMap方法完成Stream
元素匹配
提供了三種匹配方式
1.allMatch匹配所有
List?integerList?=?Arrays.asList(1,?2,?3,?4,?5);
if?(integerList.stream().allMatch(i?->?i?>?3))?{
????System.out.println("值都大于3");
}
通過allMatch方法實現(xiàn)
2.anyMatch匹配其中一個
List?integerList?=?Arrays.asList(1,?2,?3,?4,?5);
if?(integerList.stream().anyMatch(i?->?i?>?3))?{
????System.out.println("存在大于3的值");
}
等同于
for?(Integer?i?:?integerList)?{
????if?(i?>?3)?{
????????System.out.println("存在大于3的值");
????????break;
????}
}
存在大于3的值則打印,java8中通過anyMatch方法實現(xiàn)這個功能
3.noneMatch全部不匹配
List?integerList?=?Arrays.asList(1,?2,?3,?4,?5);
if?(integerList.stream().noneMatch(i?->?i?>?3))?{
????System.out.println("值都小于3");
}
通過noneMatch方法實現(xiàn)
終端操作
統(tǒng)計流中元素個數(shù)
1.通過count
List<Integer>?integerList?=?Arrays.asList(1,?2,?3,?4,?5);
Long?result?=?integerList.stream().count();
通過使用count方法統(tǒng)計出流中元素個數(shù)
2.通過counting
List<Integer>?integerList?=?Arrays.asList(1,?2,?3,?4,?5);
Long?result?=?integerList.stream().collect(counting());
最后一種統(tǒng)計元素個數(shù)的方法在與collect聯(lián)合使用的時候特別有用
查找
提供了兩種查找方式
1.findFirst查找第一個
List<Integer>?integerList?=?Arrays.asList(1,?2,?3,?4,?5);
Optional<Integer>?result?=?integerList.stream().filter(i?->?i?>?3).findFirst();
通過findFirst方法查找到第一個大于三的元素并打印
2.findAny隨機查找一個
List<Integer>?integerList?=?Arrays.asList(1,?2,?3,?4,?5);
Optional<Integer>?result?=?integerList.stream().filter(i?->?i?>?3).findAny();
通過findAny方法查找到其中一個大于三的元素并打印,因為內(nèi)部進行優(yōu)化的原因,當(dāng)找到第一個滿足大于三的元素時就結(jié)束,該方法結(jié)果和findFirst方法結(jié)果一樣。提供findAny方法是為了更好的利用并行流,findFirst方法在并行上限制更多【本篇文章將不介紹并行流】
reduce將流中的元素組合起來
假設(shè)我們對一個集合中的值進行求和
jdk8之前
int?sum?=?0;
for?(int?i?:?integerList)?{
sum?+=?i;
}
jdk8之后通過reduce進行處理
int?sum?=?integerList.stream().reduce(0,?(a,?b)?->?(a?+?b));
一行就可以完成,還可以使用方法引用簡寫成:
int?sum?=?integerList.stream().reduce(0,?Integer::sum);
reduce接受兩個參數(shù),一個初始值這里是0,一個BinaryOperator
來將兩個元素結(jié)合起來產(chǎn)生一個新值,
另外reduce方法還有一個沒有初始化值的重載方法
獲取流中最小最大值
通過min/max獲取最小最大值
Optional<Integer>?min?=?menu.stream().map(Dish::getCalories).min(Integer::compareTo);
Optional<Integer>?max?=?menu.stream().map(Dish::getCalories).max(Integer::compareTo);
也可以寫成:
OptionalInt?min?=?menu.stream().mapToInt(Dish::getCalories).min();
OptionalInt?max?=?menu.stream().mapToInt(Dish::getCalories).max();
min獲取流中最小值,max獲取流中最大值,方法參數(shù)為Comparator super T> comparator
通過minBy/maxBy獲取最小最大值
Optional<Integer>?min?=?menu.stream().map(Dish::getCalories).collect(minBy(Integer::compareTo));
Optional<Integer>?max?=?menu.stream().map(Dish::getCalories).collect(maxBy(Integer::compareTo));
minBy獲取流中最小值,maxBy獲取流中最大值,方法參數(shù)為Comparator super T> comparator
通過reduce獲取最小最大值
Optional<Integer>?min?=?menu.stream().map(Dish::getCalories).reduce(Integer::min);
Optional<Integer>?max?=?menu.stream().map(Dish::getCalories).reduce(Integer::max);
求和
通過summingInt
int?sum?=?menu.stream().collect(summingInt(Dish::getCalories));
如果數(shù)據(jù)類型為double、long,則通過summingDouble、summingLong方法進行求和
通過reduce
int?sum?=?menu.stream().map(Dish::getCalories).reduce(0,?Integer::sum);
通過sum
int?sum?=?menu.stream().mapToInt(Dish::getCalories).sum();
在上面求和、求最大值、最小值的時候,對于相同操作有不同的方法可以選擇執(zhí)行。可以選擇collect、reduce、min/max/sum方法,推薦使用min、max、sum方法。因為它最簡潔易讀,同時通過mapToInt將對象流轉(zhuǎn)換為數(shù)值流,避免了裝箱和拆箱操作
通過averagingInt求平均值
double?average?=?menu.stream().collect(averagingInt(Dish::getCalories));
如果數(shù)據(jù)類型為double、long,則通過averagingDouble、averagingLong方法進行求平均
通過summarizingInt同時求總和、平均值、最大值、最小值
IntSummaryStatistics?intSummaryStatistics?=?menu.stream().collect(summarizingInt(Dish::getCalories));
double?average?=?intSummaryStatistics.getAverage();??//獲取平均值
int?min?=?intSummaryStatistics.getMin();??//獲取最小值
int?max?=?intSummaryStatistics.getMax();??//獲取最大值
long?sum?=?intSummaryStatistics.getSum();??//獲取總和
如果數(shù)據(jù)類型為double、long,則通過summarizingDouble、summarizingLong方法
通過foreach進行元素遍歷
List?integerList?=?Arrays.asList(1,?2,?3,?4,?5);
integerList.stream().forEach(System.out::println);
而在jdk8之前實現(xiàn)遍歷:
for?(int?i?:?integerList)?{
????System.out.println(i);
}
jdk8之后遍歷元素來的更為方便,原來的for-each直接通過foreach方法就能實現(xiàn)了
返回集合
List<String>?strings?=?menu.stream().map(Dish::getName).collect(toList());
Set<String>?sets?=?menu.stream().map(Dish::getName).collect(toSet());
只舉例了一部分,還有很多其他方法 jdk8之前
?List<String>?stringList?=?new?ArrayList<>();
????Set<String>?stringSet?=?new?HashSet<>();
????for?(Dish?dish?:?menu)?{
????????stringList.add(dish.getName());
????????stringSet.add(dish.getName());
}
通過遍歷和返回集合的使用發(fā)現(xiàn)流只是把原來的外部迭代放到了內(nèi)部進行,這也是流的主要特點之一。內(nèi)部迭代可以減少好多代碼量
通過joining拼接流中的元素
String?result?=?menu.stream().map(Dish::getName).collect(Collectors.joining(",?"));
默認(rèn)如果不通過map方法進行映射處理拼接的toString方法返回的字符串,joining的方法參數(shù)為元素的分界符,如果不指定生成的字符串將是一串的,可讀性不強
進階通過groupingBy進行分組
Map>>?result?=?dishList.stream().collect(groupingBy(Dish::getType));
在collect方法中傳入groupingBy進行分組,其中g(shù)roupingBy的方法參數(shù)為分類函數(shù)。還可以通過嵌套使用groupingBy進行多級分類
MapList>?result?=?menu.stream().collect(groupingBy(Dish::getType,
????????groupingBy(dish?->?{
????????????if?(dish.getCalories()?<=?400)?return?CaloricLevel.DIET;
????????????????else?if?(dish.getCalories()?<=?700)?return?CaloricLevel.NORMAL;
????????????????else?return?CaloricLevel.FAT;
????????})));
進階通過partitioningBy進行分區(qū)
分區(qū)是特殊的分組,它分類依據(jù)是true和false,所以返回的結(jié)果最多可以分為兩組
Map<Boolean,?List>?result?=?menu.stream().collect(partitioningBy(Dish?::?isVegetarian))
等同于
Map<Boolean,?List>?result?=?menu.stream().collect(groupingBy(Dish?::?isVegetarian))
這個例子可能并不能看出分區(qū)和分類的區(qū)別,甚至覺得分區(qū)根本沒有必要,換個明顯一點的例子:
List?integerList?=?Arrays.asList(1,?2,?3,?4,?5);
MapList>?result?=?integerList.stream().collect(partitioningBy(i?->?i?3));
返回值的鍵仍然是布爾類型,但是它的分類是根據(jù)范圍進行分類的,分區(qū)比較適合處理根據(jù)范圍進行分類
總結(jié)
通過使用Stream API可以簡化代碼,同時提高了代碼可讀性,趕緊在項目里用起來。講道理在沒學(xué)Stream API之前,誰要是給我在應(yīng)用里寫很多Lambda,Stream API,飛起就想給他一腳。
我想,我現(xiàn)在可能愛上他了【嘻嘻】。同時使用的時候注意不要將聲明式和命令式編程混合使用,前幾天刷segment刷到一條:

imango老哥說的很對,別用聲明式編程的語法干命令式編程的勾當(dāng)

