<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          用Java 8 的 Stream 來寫代碼,干凈優(yōu)雅!

          共 4315字,需瀏覽 9分鐘

           ·

          2021-11-24 06:59

          Java8的新特性主要是Lambda表達式和流,當流和Lambda表達式結(jié)合起來一起使用時,因為流申明式處理數(shù)據(jù)集合的特點,可以讓代碼變得簡潔易讀



          1

          流如何簡化代碼


          如果有一個需求,需要對數(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?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之后的實現(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?MapList> beforeJdk8(List dishList) {
          ????MapList> 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以后的實現(xiàn)方式


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


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



          2

          什么是流


          流是從支持數(shù)據(jù)處理操作的源生成的元素序列,源可以是數(shù)組、文件、集合、函數(shù)。流不是集合元素,它不是數(shù)據(jù)結(jié)構(gòu)并不保存數(shù)據(jù),它的主要目的在于計算



          3

          如何生成流


          生成流的方式主要有五種


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


          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】轉(zhuǎn)換成對應的數(shù)值流,同時提供了boxed方法將數(shù)值流轉(zhuǎn)換為對象流


          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.通過函數(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,由它為流提供值。generate生成的流也是無限流,因此通過limit對流進行了截斷



          4

          流的操作類型


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


          1.中間操作


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


          2.終端操作


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



          5

          流使用


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


          中間操作


          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去除重復元素


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


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


          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 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 ->Stream的轉(zhuǎn)換


          元素匹配


          提供了三種匹配方式


          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)



          6

          終端操作


          統(tǒng)計流中元素個數(shù)


          1.通過count


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


          通過使用count方法統(tǒng)計出流中元素個數(shù)


          2.通過counting


          List 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)化的原因,當找到第一個滿足大于三的元素時就結(jié)束,該方法結(jié)果和findFirst方法結(jié)果一樣。提供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接受兩個參數(shù),一個初始值這里是0,一個BinaryOperator accumulator來將兩個元素結(jié)合起來產(chǎn)生一個新值,


          另外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獲取流中最大值,方法參數(shù)為Comparator 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獲取流中最大值,方法參數(shù)為Comparator comparator


          通過reduce獲取最小最大值


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



          7

          總結(jié)


          通過使用Stream API可以簡化代碼,同時提高了代碼可讀性,趕緊在項目里用起來



          往期推薦



          Spring Boot 接入支付寶完整流程實戰(zhàn),建議收藏!

          你試過IDEA 注釋模板這樣搞嗎

          為什么不建議使用@Async 注解?

          MySQL 性能優(yōu)化的 9 種姿勢,面試再也不怕了!

          JDK 17新特性,已發(fā)布!

          這些年我用過的 6個API 接口文檔平臺,真的好用



          瀏覽 40
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  免费无码成人片在线观看在线 | 丁香婷婷五月色成人网站 | 青青草国产视频在线观看 | 懂色av,蜜臀AV粉嫩av | 黄色一级片一级片 |