使用 Stream API 優化你的代碼

私信我,回覆:學習,獲取免費學習資源包。

放大招,流如何簡化代碼

如果有一個需求,需要對數據庫查詢到的菜餚進行一個處理:

  • 篩選出卡路里小於400的菜餚
  • 對篩選出的菜餚進行一個排序
  • 獲取排序後菜餚的名字

菜餚:Dish.java

public class Dish {
 private String name;
 private boolean vegetarian;
 private int calories;
 private Type type;
 // getter and setter
}

Java8以前的實現方式

private List 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 lowCaloricDishesName = new ArrayList<>();
 for (Dish d : lowCaloricDishes) {
 lowCaloricDishesName.add(d.getName());
 }
 return lowCaloricDishesName;
 }

Java8之後的實現方式

 private List afterJava8(List dishList) {
 return dishList.stream()
 .filter(d -> d.getCalories() < 400) //篩選出卡路里小於400的菜餚
 .sorted(comparing(Dish::getCalories)) //根據卡路里進行排序
 .map(Dish::getName) //提取菜餚名稱
 .collect(Collectors.toList()); //轉換為List
 }

不拖泥帶水,一氣呵成,原來需要寫24代碼實現的功能現在只需5行就可以完成了


使用 Stream API 優化你的代碼


高高興興寫完需求這時候又有新需求了,新需求如下:

對數據庫查詢到的菜餚根據菜餚種類進行分類,返回一個Map>的結果

這要是放在jdk8之前肯定會頭皮發麻

Java8以前的實現方式

private static Map> beforeJdk8(List dishList) {
 Map> 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,再也不用擔心複雜集合處理需求

Java8以後的實現方式

private static Map> afterJdk8(List dishList) {
 return dishList.stream().collect(groupingBy(Dish::getType));
}

又是一行代碼解決了需求,忍不住大喊Stream API牛批 看到流的強大功能了吧,接下來將詳細介紹流


使用 Stream API 優化你的代碼


什麼是流

流是從支持數據處理操作的源生成的元素序列,源可以是數組、文件、集合、函數。流不是集合元素,它不是數據結構並不保存數據,它的主要目的在於計算

如何生成流

生成流的方式主要有五種

1.通過集合生成,應用中最常用的一種

List integerList = Arrays.asList(1, 2, 3, 4, 5);
Stream stream = integerList.stream();

通過集合的stream方法生成流

2.通過數組生成

int[] intArr = new int[]{1, 2, 3, 4, 5};
IntStream stream = Arrays.stream(intArr);

通過Arrays.stream方法生成流,並且該方法生成的流是數值流【即IntStream】而不是Stream。補充一點使用數值流可以避免計算過程中拆箱裝箱,提高性能。

Stream API提供了mapToInt、mapToDouble、mapToLong三種方式將對象流【即Stream】轉換成對應的數值流,同時提供了boxed方法將數值流轉換為對象流

3.通過值生成

Stream 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.通過函數生成 提供了iterate和generate兩個靜態方法從函數中生成流

iterator

Stream stream = Stream.iterate(0, n -> n + 2).limit(5);

iterate方法接受兩個參數,第一個為初始化值,第二個為進行的函數操作,因為iterator生成的流為無限流,通過limit方法對流進行了截斷,只生成5個偶數

generator

Stream stream = Stream.generate(Math::random).limit(5);

generate方法接受一個參數,方法參數類型為Supplier,由它為流提供值。generate生成的流也是無限流,因此通過limit對流進行了截斷

使用 Stream API 優化你的代碼

流的操作類型

流的操作類型主要分為兩種

1.中間操作

一個流可以後面跟隨零個或多箇中間操作。其目的主要是打開流,做出某種程度的數據映射/過濾,然後返回一個新的流,交給下一個操作使用。這類操作都是惰性化的,僅僅調用到這類方法,並沒有真正開始流的遍歷,真正的遍歷需等到終端操作時,常見的中間操作有下面即將介紹的filter、map等

2.終端操作

一個流有且只能有一個終端操作,當這個操作執行後,流就被關閉了,無法再被操作,因此一個流只能被遍歷一次,若想在遍歷需要通過源數據在生成流。終端操作的執行,才會真正開始流的遍歷。如下面即將介紹的count、collect等

流使用

流的使用將分為終端操作和中間操作進行介紹

中間操作

filter篩選

 List integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
 Stream stream = integerList.stream().filter(i -> i > 3);

通過使用filter方法進行條件篩選,filter的方法參數為一個條件

distinct去除重複元素

List integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
Stream stream = integerList.stream().distinct();

通過distinct方法快速去除重複的元素

limit返回指定流個數

 List integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
 Stream stream = integerList.stream().limit(3);

通過limit方法指定返回流的個數,limit的參數值必須>=0,否則將會拋出異常

skip跳過流中的元素

 List integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
 Stream stream = integerList.stream().skip(2);

通過skip方法跳過流中的元素,上述例子跳過前兩個元素,所以打印結果為2,3,4,5,skip的參數值必須>=0,否則將會拋出異常

map流映射

所謂流映射就是將接受的元素映射成另外一個元素

List stringList = Arrays.asList("Java 8", "Lambdas", "In", "Action");
Stream stream = stringList.stream().map(String::length);

通過map方法可以完成映射,該例子完成中String -> Integer的映射,之前上面的例子通過map方法完成了Dish->String的映射

flatMap流轉換

將一個流中的每個值都轉換為另一個流

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 ->Stream的轉換

元素匹配

提供了三種匹配方式

1.allMatch匹配所有

List integerList = Arrays.asList(1, 2, 3, 4, 5);
if (integerList.stream().allMatch(i -> i > 3)) {
 System.out.println("值都大於3");
}
 

通過allMatch方法實現

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方法實現這個功能

3.noneMatch全部不匹配

List integerList = Arrays.asList(1, 2, 3, 4, 5);
if (integerList.stream().noneMatch(i -> i > 3)) {
 System.out.println("值都小於3");
}

通過noneMatch方法實現

使用 Stream API 優化你的代碼

終端操作

統計流中元素個數

1.通過count

List integerList = Arrays.asList(1, 2, 3, 4, 5);
Long result = integerList.stream().count();

通過使用count方法統計出流中元素個數

2.通過counting

List integerList = Arrays.asList(1, 2, 3, 4, 5);
Long result = integerList.stream().collect(counting());

最後一種統計元素個數的方法在與collect聯合使用的時候特別有用

查找

提供了兩種查找方式

1.findFirst查找第一個

List integerList = Arrays.asList(1, 2, 3, 4, 5);
Optional result = integerList.stream().filter(i -> i > 3).findFirst();

通過findFirst方法查找到第一個大於三的元素並打印

2.findAny隨機查找一個

List integerList = Arrays.asList(1, 2, 3, 4, 5);
Optional result = integerList.stream().filter(i -> i > 3).findAny();

通過findAny方法查找到其中一個大於三的元素並打印,因為內部進行優化的原因,當找到第一個滿足大於三的元素時就結束,該方法結果和findFirst方法結果一樣。提供findAny方法是為了更好的利用並行流,findFirst方法在並行上限制更多【本篇文章將不介紹並行流】

reduce將流中的元素組合起來

假設我們對一個集合中的值進行求和

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接受兩個參數,一個初始值這裡是0,一個BinaryOperator accumulator

來將兩個元素結合起來產生一個新值,

另外reduce方法還有一個沒有初始化值的重載方法

獲取流中最小最大值

通過min/max獲取最小最大值

Optional min = menu.stream().map(Dish::getCalories).min(Integer::compareTo);
Optional 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獲取流中最大值,方法參數為Comparator super T> comparator

通過minBy/maxBy獲取最小最大值

Optional min = menu.stream().map(Dish::getCalories).collect(minBy(Integer::compareTo));
Optional max = menu.stream().map(Dish::getCalories).collect(maxBy(Integer::compareTo));

minBy獲取流中最小值,maxBy獲取流中最大值,方法參數為Comparator super T> comparator

通過reduce獲取最小最大值

Optional min = menu.stream().map(Dish::getCalories).reduce(Integer::min);
Optional max = menu.stream().map(Dish::getCalories).reduce(Integer::max);

求和

通過summingInt

int sum = menu.stream().collect(summingInt(Dish::getCalories));

如果數據類型為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();

在上面求和、求最大值、最小值的時候,對於相同操作有不同的方法可以選擇執行。可以選擇collect、reduce、min/max/sum方法,推薦使用min、max、sum方法。因為它最簡潔易讀,同時通過mapToInt將對象流轉換為數值流,避免了裝箱和拆箱操作

通過averagingInt求平均值

double average = menu.stream().collect(averagingInt(Dish::getCalories));

如果數據類型為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(); //獲取總和

如果數據類型為double、long,則通過summarizingDouble、summarizingLong方法

通過foreach進行元素遍歷

List integerList = Arrays.asList(1, 2, 3, 4, 5);
integerList.stream().forEach(System.out::println);

而在jdk8之前實現遍歷:

for (int i : integerList) {
 System.out.println(i);
}

jdk8之後遍歷元素來的更為方便,原來的for-each直接通過foreach方法就能實現了

返回集合

List strings = menu.stream().map(Dish::getName).collect(toList());
Set sets = menu.stream().map(Dish::getName).collect(toSet());

只舉例了一部分,還有很多其他方法 jdk8之前

 List stringList = new ArrayList<>();
 Set stringSet = new HashSet<>();
 for (Dish dish : menu) {
 stringList.add(dish.getName());
 stringSet.add(dish.getName());
}

通過遍歷和返回集合的使用發現流只是把原來的外部迭代放到了內部進行,這也是流的主要特點之一。內部迭代可以減少好多代碼量

通過joining拼接流中的元素

String result = menu.stream().map(Dish::getName).collect(Collectors.joining(", "));

默認如果不通過map方法進行映射處理拼接的toString方法返回的字符串,joining的方法參數為元素的分界符,如果不指定生成的字符串將是一串的,可讀性不強

進階通過groupingBy進行分組

Map> result = dishList.stream().collect(groupingBy(Dish::getType));

在collect方法中傳入groupingBy進行分組,其中groupingBy的方法參數為分類函數。還可以通過嵌套使用groupingBy進行多級分類

Map> 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進行分區

分區是特殊的分組,它分類依據是true和false,所以返回的結果最多可以分為兩組

Map> result = menu.stream().collect(partitioningBy(Dish :: isVegetarian))

等同於

Map> result = menu.stream().collect(groupingBy(Dish :: isVegetarian))

這個例子可能並不能看出分區和分類的區別,甚至覺得分區根本沒有必要,換個明顯一點的例子:

List integerList = Arrays.asList(1, 2, 3, 4, 5);
Map> result = integerList.stream().collect(partitioningBy(i -> i < 3));

返回值的鍵仍然是布爾類型,但是它的分類是根據範圍進行分類的,分區比較適合處理根據範圍進行分類

使用 Stream API 優化你的代碼

總結

通過使用Stream API可以簡化代碼,同時提高了代碼可讀性,趕緊在項目裡用起來。講道理在沒學Stream API之前,誰要是給我在應用裡寫很多Lambda,Stream API,飛起就想給他一腳。

我想,我現在可能愛上他了【嘻嘻】。同時使用的時候注意不要將聲明式和命令式編程混合使用,前幾天刷segment刷到一條:


使用 Stream API 優化你的代碼


imango老哥說的很對,別用聲明式編程的語法幹命令式編程的勾當


使用 Stream API 優化你的代碼

來源網絡,侵權聯繫刪除

私信我,回覆:學習,獲取免費學習資源包。


分享到:


相關文章: