java中lambda表達式的使用案例技巧


1、【Functional Interface】:一個接口僅有一個抽象方法,比如Runnable、Comparator等。在任何一個需要Functional Interface對象的地方,都可以使用lambda表達式。

2、【Method Reference】:將lambda表達式的參數作爲參數傳遞給一個方法,他們的執行效果是相同的,則該lambda表達式
可以使用Method Reference表達,以下兩種方式是等價的:

  (x) -> System.out.println(x)
  System.out::println

 

  Method Reference主要有三種形式:
    1.Object::instanceMethod
    2.Class::staticMethod
    3.Class::instanceMethod

  對於前兩種方式,對應的lambda表達式的參數和method的參數是一致的,比如:

  System.out::println
  (x) -> System.out.println(x)


  Math::pow 

  (x, y) -> Math.pow(x, y)


  對於第三種方式,對應的lambda表達式的語句體中,第一個參數作爲對象,調用method,將其它參數

  String::compareToIgnoreCase
  (s1, s2) -> s1.compareToIgnoreCase(s2)


  Constructor Reference與Method Reference類似,只不過是特殊的method:new,具體調用的是哪個構造函數,由上下文環境決定,比如:

  List<String> labels = ...;
  Stream<Button> stream = labels.stream().map(Button::new);

  Button::new等價於(x) -> Button(x),所以調用的構造函數是:Button(x);
  除了創建單個對象,也可以創建對象數組,如下面兩種方式等價:

  int[]::new 
  (x) -> new int[x]

====== Map ======

1、map遍歷

itemsMap.forEach((k,v)->System.out.println("Item : " + k + " Count : " + v));


====== List ======

1、List排序

  1)、list升序

    //原始版
    words.sort((Word first, Word second) -> first.getName().compareTo(second.getName()));
    //精簡版
    Collections.sort(words, Comparator.comparing(Word::getName));
    //精簡版,推薦使用這種
    words.sort(Comparator.comparing(Word::getName));
    //多重排序(連個都升序)
    words.sort(Comparator.comparing(Word::getName).thenComparingInt(Word::getCountry));
    //多重排序(第一個升,第二個降)
    words.sort(Comparator.comparing(Word::getName).reversed().thenComparingInt(Word::getCountry).reversed());


  2)、list降序

words.sort(Comparator.comparing(Word::getName).reversed());

 

2、list遍歷

words.forEach(System.out::println);

 

3、list轉Map(key去重)

Map<String, Word> wordMapMap = wordList.stream().collect(Collectors.toMap(Word::getName, k -> k, (k1, k2) -> k1));


   list轉Map(key不能重複)

Map<Integer,Word> userMap = wordList.stream().collect(Collectors.toMap(Word::getCountry, k -> k));

 

4、分組

Map<String, List<Word>> groupMap = wordList.stream().collect(Collectors.groupingBy(Word::getName));


   多重分組

Map<String, Map<Integer, List<Word>>> map2 = words.stream().collect(Collectors.groupingBy(Word::getName,Collectors.groupingBy(Word::getCountry)));

 

5、匹配過濾

List<Word> filterList = wordList.stream().filter(v -> v.getName().equals("tiger")).collect(Collectors.toList());

 

wordList.stream().filter(v -> v.getName().contains("老")).forEach(System.out::println);

 

List<Word> filterList = wordList.stream().filter(v -> v.getCountry() > 2).collect(Collectors.toList());

 

             Predicate<Word> equals1 = v -> v.getCountry().equals(1);
             Predicate<Word> contains1 = v -> v.getName().contains("tiger");
             List<Word> filterList = wordList.stream().filter(contains1.and(equals1)).collect(Collectors.toList());

 

List<Double> filteredCost = cost.stream().filter(x -> x > 25.0).collect(Collectors.toList());

 

6、list統計求和

int sum = wordList.stream().mapToInt(Word::getCountry).sum();

 

double sum = words.stream().mapToDouble(Word::getCountry).sum();

 

7、分組統計個數

Map<String, Long> collectCnt = wordList.stream().collect(Collectors.groupingBy(Word::getName, Collectors.counting()));

 

8、分組統計

Map<String, LongSummaryStatistics> map3 = words.stream().collect(Collectors.groupingBy(Word::getName,Collectors.summarizingLong(Word::getCountry)));

 

  多重分組統計

Map<String, Map<Integer, LongSummaryStatistics>> map3 = words.stream().collect(Collectors.groupingBy(Word::getName,Collectors.groupingBy(Word::getCountry,Collectors.summarizingLong(Word::getCountry))));

 

9、去重(需根據實際情況重寫Word的equals與hashCode)

List<Word> list1= list.stream().distinct().collect(Collectors.toList());


    
10、數據拼裝

String result = words.stream().map(Word::getName).collect(Collectors.joining("," , "[" , "]"));

 

12、對象集合轉屬性集合

List<String> result = words.stream().map(Word::getName).collect(Collectors.toList());

 

List<String> result = words.stream().map(y -> y.getName().concat(".jpg")).collect(Collectors.toList());


        
====== 數組 ======

1、數組排序
  1)、數組升序->原始版

Arrays.sort(people, (first, second) -> Integer.compare(first.length(),  second.length()));


      數組升序->精簡版

Arrays.sort(people, Comparator.comparingInt(String::hashCode));


  2)、數組降序

Arrays.sort(people, (second, first) -> Integer.compare(first.length(), second.length()));

 

2、數組統計某元素個數

long num = Arrays.stream(name).filter(x -> x.equals("tiger")).count();

 

3、數組去重過濾並轉化成集合

List<String> filterList = Arrays.stream(name).filter(x -> !x.equals("趙強")).collect(Collectors.toList());

 

4、數組過濾,並對元素加後綴

List<String> filterList = Arrays.stream(name).filter(x -> !x.equals("tiger")).map(y -> y.concat(".jpg")).collect(Collectors.toList());

 

5、數組統計求和 

int num = Arrays.stream(arr).reduce(0, Integer::sum);

 

double sum =  Arrays.asList(10.0, 20.0, 30.0).stream().map(x -> x + x * 0.05).reduce(Double::sum).get();

 

double sum = Stream.of(10.0, 20.0, 30.0).map(x -> x + x * 0.05).reduce(Double::sum).get();

 

int sum = Stream.of(1, 2, 3, 4, 5).map(x -> x + x * 5).reduce(Integer::sum).get();

 

====== 求和 ======

  BinaryOperator<Integer> add = Integer::sum;
  Integer x = add.apply(20, 30);


====== 線程 ======

    private static void lambdaRunnable() {
        int age = 20;
        Runnable r2 = () -> {
            System.out.println(age);
            System.out.println("Hello world two!"+age);
        };
        r2.run();
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章