Use case skills of lambda expressions in java


1. [Functional Interface]: An interface has only one abstract method, such as Runnable, Comparator, etc. Wherever a Functional Interface object is needed, lambda expressions can be used.

2. [Method Reference]: Pass the parameters of the lambda expression as a parameter to a method, and their execution effect is the same, then the lambda expression
can be expressed using the Method Reference. The following two methods are equivalent:

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

 

  Method Reference mainly has three forms:
    1.Object::instanceMethod
    2.Class::staticMethod
    3.Class::instanceMethod

  For the first two methods, the corresponding lambda expression parameters and method parameters are the same, for example:

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


  Math::pow 

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


  For the third method, in the statement body of the corresponding lambda expression, the first parameter is used as the object, the method is called, and the other parameters are

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


  Constructor Reference is similar to Method Reference, except that it is a special method: new. Which constructor is called depends on the context, such as:

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

  Button::new is equivalent to (x) -> Button(x), so the called constructor is: Button(x);
  In addition to creating a single object, you can also create an array of objects. The following two methods are equivalent:

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

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

1. Map traversal

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


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

1. List sorting

  1), list ascending

    //原始版
    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 descending

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

 

2. List traversal

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

 

3. List to Map (key deduplication)

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


   List to Map (key cannot be repeated)

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

 

4. Group

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


   Multiple grouping

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

 

5. Match filtering

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 statistics summation

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

 

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

 

7. Group statistics

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

 

8. Group statistics

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

 

  Multiple grouping statistics

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

 

9. Deduplication (rewrite the equals and hashCode of Word according to the actual situation)

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


    
10. Data assembly

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

 

12. Object collection to attribute collection

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());


        
====== Array ======

1. Array sorting
  1), ascending array order -> original version

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


      Array ascending -> Lite version

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


  2), array descending

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

 

2. Array counts the number of certain elements

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

 

3. The array is filtered and converted into a collection

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

 

4. Array filtering and adding suffixes to elements

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

 

5. Array statistical summation 

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();

 

====== Sum ======

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


====== Thread ======

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

 

Guess you like

Origin blog.csdn.net/qq_36336332/article/details/106455729