1. <strong id="7actg"></strong>
    2. <table id="7actg"></table>

    3. <address id="7actg"></address>
      <address id="7actg"></address>
      1. <object id="7actg"><tt id="7actg"></tt></object>

        聊聊工作中常用的Lambda表達式

        共 9643字,需瀏覽 20分鐘

         ·

        2022-12-30 09:01

        前言

        大家好,我是田螺。

        日常開發(fā)中,我們很多時候需要用到Java 8Lambda表達式,它允許把函數(shù)作為一個方法的參數(shù),讓我們的代碼更優(yōu)雅、更簡潔。所以整理了一波工作中,我常用的,有哪些Lambda表達式??赐暌欢〞袔椭摹?/p>

        1. list轉map

        工作中,我們經(jīng)常遇到listmap的案例。Collectors.toMap就可以把一個list數(shù)組轉成一個Map。代碼如下:

              
              public?class?TestLambda?{

        ????public?static?void?main(String[]?args)?{

        ????????List<UserInfo>?userInfoList?=?new?ArrayList<>();
        ????????userInfoList.add(new?UserInfo(1L,?"撿田螺的小男孩",?18));
        ????????userInfoList.add(new?UserInfo(2L,?"程序員田螺",?27));
        ????????userInfoList.add(new?UserInfo(2L,?"撿瓶子的小男孩",?26));

        ????????/**
        ?????????*??list?轉?map
        ?????????*??使用Collectors.toMap的時候,如果有可以重復會報錯,所以需要加(k1,?k2)?->?k1
        ?????????*??(k1,?k2)?->?k1?表示,如果有重復的key,則保留第一個,舍棄第二個
        ?????????*/
        ????????Map<Long,?UserInfo>?userInfoMap?=?userInfoList.stream().collect(Collectors.toMap(UserInfo::getUserId,?userInfo?->?userInfo,?(k1,?k2)?->?k1));
        ????????userInfoMap.values().forEach(a->System.out.println(a.getUserName()));
        ????}
        }

        //運行結果
        撿田螺的小男孩
        程序員田螺

        類似的,還有Collectors.toList()、Collectors.toSet(),表示把對應的流轉化為list或者Set。

        2. filter()過濾

        從數(shù)組集合中,過濾掉不符合條件的元素,留下符合條件的元素。

              
              List<UserInfo>?userInfoList?=?new?ArrayList<>();
        userInfoList.add(new?UserInfo(1L,?"撿田螺的小男孩",?18));
        userInfoList.add(new?UserInfo(2L,?"程序員田螺",?27));
        userInfoList.add(new?UserInfo(3L,?"撿瓶子的小男孩",?26));
        ????????
        /**
        ?*?filter?過濾,留下超過18歲的用戶
        ?*/
        List<UserInfo>?userInfoResultList?=?userInfoList.stream().filter(user?->?user.getAge()?>?18).collect(Collectors.toList());
        userInfoResultList.forEach(a?->?System.out.println(a.getUserName()));
        ????????
        //運行結果
        程序員田螺
        撿瓶子的小男孩

        3. foreach遍歷

        foreach 遍歷list,遍歷map,真的很絲滑。

              
              /**
        ?*?forEach?遍歷集合List列表
        ?*/
        List<String>?userNameList?=?Arrays.asList("撿田螺的小男孩",?"程序員田螺",?"撿瓶子的小男孩");
        userNameList.forEach(System.out::println);
        ?
        HashMap<String,?String>?hashMap?=?new?HashMap<>();
        hashMap.put("公眾號",?"撿田螺的小男孩");
        hashMap.put("職業(yè)",?"程序員田螺");
        hashMap.put("昵稱",?"撿瓶子的小男孩");
        /**
        ?*??forEach?遍歷集合Map
        ?*/
        hashMap.forEach((k,?v)?->?System.out.println(k?+?":\t"?+?v));

        //運行結果
        撿田螺的小男孩
        程序員田螺
        撿瓶子的小男孩
        職業(yè):?程序員田螺
        公眾號:?撿田螺的小男孩
        昵稱:?撿瓶子的小男孩

        4. groupingBy分組

        提到分組,相信大家都會想起SQLgroup by。我們經(jīng)常需要一個List做分組操作。比如,按城市分組用戶。在Java8之前,是這么實現(xiàn)的:

              
              List<UserInfo>?originUserInfoList?=?new?ArrayList<>();
        originUserInfoList.add(new?UserInfo(1L,?"撿田螺的小男孩",?18,"深圳"));

        originUserInfoList.add(new?UserInfo(3L,?"撿瓶子的小男孩",?26,"湛江"));
        originUserInfoList.add(new?UserInfo(2L,?"程序員田螺",?27,"深圳"));
        Map<String,?List<UserInfo>>?result?=?new?HashMap<>();
        for?(UserInfo?userInfo?:?originUserInfoList)?{
        ??String?city?=?userInfo.getCity();
        ??List<UserInfo>?userInfos?=?result.get(city);
        ??if?(userInfos?==?null)?{
        ??????userInfos?=?new?ArrayList<>();
        ??????result.put(city,?userInfos);
        ????}
        ??userInfos.add(userInfo);
        }

        而使用Java8的groupingBy分組器,清爽無比:

              
              Map<String,?List<UserInfo>>?result?=?originUserInfoList.stream()
        .collect(Collectors.groupingBy(UserInfo::getCity));

        5. sorted+Comparator 排序

        工作中,排序的需求比較多,使用sorted+Comparator排序,真的很香。

              
              List<UserInfo>?userInfoList?=?new?ArrayList<>();
        userInfoList.add(new?UserInfo(1L,?"撿田螺的小男孩",?18));
        userInfoList.add(new?UserInfo(3L,?"撿瓶子的小男孩",?26));
        userInfoList.add(new?UserInfo(2L,?"程序員田螺",?27));

        /**
        ?*??sorted?+?Comparator.comparing?排序列表,
        ?*/
        userInfoList?=?userInfoList.stream().sorted(Comparator.comparing(UserInfo::getAge)).collect(Collectors.toList());
        userInfoList.forEach(a?->?System.out.println(a.toString()));

        System.out.println("開始降序排序");

        /**
        ?*?如果想降序排序,則可以使用加reversed()
        ?*/
        userInfoList?=?userInfoList.stream().sorted(Comparator.comparing(UserInfo::getAge).reversed()).collect(Collectors.toList());
        userInfoList.forEach(a?->?System.out.println(a.toString()));

        //運行結果
        UserInfo{userId=1,?userName='撿田螺的小男孩',?age=18}
        UserInfo{userId=3,?userName='撿瓶子的小男孩',?age=26}
        UserInfo{userId=2,?userName='程序員田螺',?age=27}
        開始降序排序
        UserInfo{userId=2,?userName='程序員田螺',?age=27}
        UserInfo{userId=3,?userName='撿瓶子的小男孩',?age=26}
        UserInfo{userId=1,?userName='撿田螺的小男孩',?age=18}

        6.distinct去重

        distinct可以去除重復的元素:

              
              List<String>?list?=?Arrays.asList("A",?"B",?"F",?"A",?"C");
        List<String>?temp?=?list.stream().distinct().collect(Collectors.toList());
        temp.forEach(System.out::println);

        7. findFirst 返回第一個

        findFirst 很多業(yè)務場景,我們只需要返回集合的第一個元素即可:

              
              List<String>?list?=?Arrays.asList("A",?"B",?"F",?"A",?"C");
        list.stream().findFirst().ifPresent(System.out::println);

        8. anyMatch是否至少匹配一個元素

        anyMatch 檢查流是否包含至少一個滿足給定謂詞的元素。

              
              Stream<String>?stream?=?Stream.of("A",?"B",?"C",?"D");
        boolean?match?=?stream.anyMatch(s?->?s.contains("C"));
        System.out.println(match);
        //輸出
        true

        9. allMatch 匹配所有元素

        allMatch 檢查流是否所有都滿足給定謂詞的元素。

              
              Stream<String>?stream?=?Stream.of("A",?"B",?"C",?"D");
        boolean?match?=?stream.allMatch(s?->?s.contains("C"));
        System.out.println(match);
        //輸出
        false

        10. map轉換

        map方法可以幫我們做元素轉換,比如一個元素所有字母轉化為大寫,又或者把獲取一個元素對象的某個屬性,demo如下:

              
              List<String>?list?=?Arrays.asList("jay",?"tianluo");
        //轉化為大寫
        List<String>?upperCaselist?=?list.stream().map(String::toUpperCase).collect(Collectors.toList());
        upperCaselist.forEach(System.out::println);

        11. Reduce

        Reduce可以合并流的元素,并生成一個值

              
              int?sum?=?Stream.of(1,?2,?3,?4).reduce(0,?(a,?b)?->?a?+?b);
        System.out.println(sum);

        12. peek 打印個日志

        peek()方法是一個中間Stream操作,有時候我們可以使用peek來打印日志。

              
              List<String>?result?=?Stream.of("程序員田螺",?"撿田螺的小男孩",?"撿瓶子的小男孩")
        ????????????.filter(a?->?a.contains("田螺"))
        ????????????.peek(a?->?System.out.println("關注公眾號:"?+?a)).collect(Collectors.toList());
        System.out.println(result);
        //運行結果
        關注公眾號:程序員田螺
        關注公眾號:撿田螺的小男孩
        [程序員田螺,?撿田螺的小男孩]

        13. Max,Min最大最小

        使用lambda流求最大,最小值,非常方便。

              
              List<UserInfo>?userInfoList?=?new?ArrayList<>();
        userInfoList.add(new?UserInfo(1L,?"撿田螺的小男孩",?18));
        userInfoList.add(new?UserInfo(3L,?"撿瓶子的小男孩",?26));
        userInfoList.add(new?UserInfo(2L,?"程序員田螺",?27));

        Optional<UserInfo>?maxAgeUserInfoOpt?=?userInfoList.stream().max(Comparator.comparing(UserInfo::getAge));
        maxAgeUserInfoOpt.ifPresent(userInfo?->?System.out.println("max?age user:"?+?userInfo));

        Optional<UserInfo>?minAgeUserInfoOpt?=?userInfoList.stream().min(Comparator.comparing(UserInfo::getAge));
        minAgeUserInfoOpt.ifPresent(userInfo?->?System.out.println("min?age user:"?+?userInfo));

        //運行結果
        max?age user:UserInfo{userId=2,?userName='程序員田螺',?age=27}
        min?age user:UserInfo{userId=1,?userName='撿田螺的小男孩',?age=18}

        14. count統(tǒng)計

        一般count()表示獲取流數(shù)據(jù)元素總數(shù)。

              
              List<UserInfo>?userInfoList?=?new?ArrayList<>();
        userInfoList.add(new?UserInfo(1L,?"撿田螺的小男孩",?18));
        userInfoList.add(new?UserInfo(3L,?"撿瓶子的小男孩",?26));
        userInfoList.add(new?UserInfo(2L,?"程序員田螺",?27));

        long?count?=?userInfoList.stream().filter(user?->?user.getAge()?>?18).count();
        System.out.println("大于18歲的用戶:"?+?count);
        //輸出
        大于18歲的用戶:2

        15. 常用函數(shù)式接口

        其實lambda離不開函數(shù)式接口,我們來看下JDK8常用的幾個函數(shù)式接口:

        • Function<T, R>(轉換型): 接受一個輸入?yún)?shù),返回一個結果
        • Consumer<T> (消費型): 接收一個輸入?yún)?shù),并且無返回操作
        • Predicate<T> (判斷型): 接收一個輸入?yún)?shù),并且返回布爾值結果
        • Supplier<T> (供給型): 無參數(shù),返回結果

        Function<T, R> 是一個功能轉換型的接口,可以把將一種類型的數(shù)據(jù)轉化為另外一種類型的數(shù)據(jù)

              
              ????private?void?testFunction()?{
        ????????//獲取每個字符串的長度,并且返回
        ????????Function<String,?Integer>?function?=?String::length;
        ????????Stream<String>?stream?=?Stream.of("程序員田螺",?"撿田螺的小男孩",?"撿瓶子的小男孩");
        ????????Stream<Integer>?resultStream?=?stream.map(function);
        ????????resultStream.forEach(System.out::println);
        ????}

        Consumer<T>是一個消費性接口,通過傳入?yún)?shù),并且無返回的操作

              
              ???private?void?testComsumer()?{
        ????????//獲取每個字符串的長度,并且返回
        ????????Consumer<String>?comsumer?=?System.out::println;
        ????????Stream<String>?stream?=?Stream.of("程序員田螺",?"撿田螺的小男孩",?"撿瓶子的小男孩");
        ????????stream.forEach(comsumer);
        ????}

        Predicate<T>是一個判斷型接口,并且返回布爾值結果.

              
              ????private?void?testPredicate()?{
        ????????//獲取每個字符串的長度,并且返回
        ????????Predicate<Integer>?predicate?=?a?->?a?>?18;
        ????????UserInfo?userInfo?=?new?UserInfo(2L,?"程序員田螺",?27);
        ????????System.out.println(predicate.test(userInfo.getAge()));
        ????}

        Supplier<T>是一個供給型接口,無參數(shù),有返回結果。

              
              ????private?void?testSupplier()?{
        ????????Supplier<Integer>?supplier?=?()?->?Integer.valueOf("666");
        ????????System.out.println(supplier.get());
        ????}

        這幾個函數(shù)在日常開發(fā)中,也是可以靈活應用的,比如我們DAO操作完數(shù)據(jù)庫,是會有個result的整型結果返回。我們就可以用Supplier<T>來統(tǒng)一判斷是否操作成功。如下:

              
              ????private?void?saveDb(Supplier<Integer>?supplier)?{
        ????????if?(supplier.get()?>?0)?{
        ????????????System.out.println("插入數(shù)據(jù)庫成功");
        ????????}else{
        ????????????System.out.println("插入數(shù)據(jù)庫失敗");
        ????????}
        ????}
        ????
        ????@Test
        ????public?void?add()?throws?Exception?{
        ????????Course?course=new?Course();
        ????????course.setCname("java");
        ????????course.setUserId(100L);
        ????????course.setCstatus("Normal");
        ????????saveDb(()?->?courseMapper.insert(course));
        ????}

        最后

        本文我們介紹了,工作中常用的十幾種Lambda 表達式的使用。如果對你有幫助,麻煩給個三連(點贊、在看、轉發(fā))。一起加油

        瀏覽 78
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

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

        手機掃一掃分享

        分享
        舉報
        1. <strong id="7actg"></strong>
        2. <table id="7actg"></table>

        3. <address id="7actg"></address>
          <address id="7actg"></address>
          1. <object id="7actg"><tt id="7actg"></tt></object>
            久久久国产精品无码动漫 | 黑丝美女被爆艹 | 青娱乐偷拍 | 成人影片中文字幕 | 日韩无码家庭乱伦 | 成人一卡二卡 | 91丝袜高潮流白浆潮喷在线观看 | 欧美日韩在线免费观看 | 成人毛片免费观看完高清完整版 | 台湾又色又爽又黄的大片网站 |