lambda表達式使用解析

1、Predicate/Consumer/Function/Supplier介紹

Predicate boolean test(T t);
Consumer accpet(T t);
Function<T, R> R apply(T t);
Supplier<T> T get();

以Predicate爲例,引申出很多類似的Predicate,如IntPredicate、DoublePredicate、BiPredicate、LongPredicate。但是他們的用法都是差不多的。比較類似。

 

2、舉例子:

package com.cy.java8;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.*;

public class LambdaUsage {

    private static List<Apple> filter(List<Apple> source, Predicate<Apple> predicate){
        List<Apple> result = new ArrayList<>();
        for(Apple a : source){
            if(predicate.test(a)){
                result.add(a);
            }
        }
        return result;
    }

    //根據一個long類型的參數過濾
    private static List<Apple> filterByWeight(List<Apple> source, LongPredicate predicate){
        List<Apple> result = new ArrayList<>();
        for(Apple a : source){
            if(predicate.test(a.getWeight())){
                result.add(a);
            }
        }
        return result;
    }

    //根據兩個參數過濾
    private static List<Apple> filterByColorWeight(List<Apple> source, BiPredicate<String, Long> bipredicate){
        List<Apple> result = new ArrayList<>();
        for(Apple a : source){
            if(bipredicate.test(a.getColor(), a.getWeight())){
                result.add(a);
            }
        }
        return result;
    }

    private static void simpleTestConsumer(List<Apple> source, Consumer<Apple> consumer){
        for(Apple a : source){
            consumer.accept(a);
        }
    }

    private static String testFunction(Apple apple, Function<Apple, String> fun){
        return fun.apply(apple);
    }

    public static void main(String[] args) {
        List<Apple> list = Arrays.asList(new Apple("green", 120), new Apple("red", 150));
        List<Apple> greenList = filter(list, apple -> apple.getColor().equals("green"));
        System.out.println(greenList);

        System.out.println("-----------------------------");
        List<Apple> weightList = filterByWeight(list, weight -> weight>=150);
        System.out.println(weightList);

        System.out.println("-----------------------------");
        List<Apple> result = filterByColorWeight(list, (color, weight) -> color.equals("red") && weight > 100);
        System.out.println(result);

        System.out.println("-----------------------------");
        simpleTestConsumer(list, apple -> System.out.println("print apple's string method: " +apple));

        System.out.println("-----------------------------");
        String color = testFunction(new Apple("yellow", 10), apple -> apple.getColor());
        System.out.println(color);

        System.out.println("-----------------------------");
        Supplier<String> supplier = String::new;
        System.out.println(supplier.get().getClass());
    }

}

打印結果:

[Apple(color=green, weight=120)]
-----------------------------
[Apple(color=red, weight=150)]
-----------------------------
[Apple(color=red, weight=150)]
-----------------------------
print apple's string method: Apple(color=green, weight=120)
print apple's string method: Apple(color=red, weight=150)
-----------------------------
yellow
-----------------------------
class java.lang.String

3、方法推導解析      

什麼情況下允許方法推導的方式來寫呢?
1.可以通過一個類的靜態方法,比如Integer::parseInt
2.可以通過一個類的成員方法。
3.可以通過一個類的實例的方法。
4.可以通過構造函數的推導。

舉例子:

package com.cy.java8;

import lombok.Data;

@Data
public class ComplexApple {
    private String color;
    private long weight;
    private String name;

    public ComplexApple(String color, long weight, String name) {
        this.color = color;
        this.weight = weight;
        this.name = name;
    }
}
View Code
package com.cy.java8;

@FunctionalInterface
public interface ThreeParamFuntion<T, U, K, R> {

    R apply(T t, U u, K k);
}
View Code
package com.cy.java8;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Stream;

public class MethodReference {

    public static void main(String[] args) {
        /*Consumer<String> consumer = s -> System.out.println(s);
        useConsumer(consumer,"hello alex");*/

        useConsumer(s -> System.out.println(s),"hello alex");
        useConsumer(System.out::println, "hello today");

        List<Apple> list = Arrays.asList(new Apple("green", 120), new Apple("abc", 100), new Apple("red", 150));
        System.out.println(list);
        list.sort((a1, a2) -> a1.getColor().compareTo(a2.getColor()));
        System.out.println(list);
        
        //比如循環輸出apple信息
        list.stream().forEach(apple -> System.out.println(apple));
        
        //可以改成成如下
        System.out.println("-----------------------------------------");
        list.stream().forEach(System.out::println);
        System.out.println("-----------------------------------------");

        //方法推導,通過一個類的靜態方法
        Function<String, Integer> funtion = Integer::parseInt;
        int result = funtion.apply("123");
        System.out.println(result);

        //方法推導,通過一個類的成員方法
        BiFunction<String, Integer, Character> f1 = String::charAt;
        System.out.println(f1.apply("index", 0));

        //方法推導,通過一個類的實例的方法
        String s = new String("index");
        Function<Integer, Character> f2 = s::charAt;
        System.out.println(f2.apply(1));

        //通過構造函數的推導
        Supplier<String> s1 = String::new;
        System.out.println(s1.get().getClass().getSimpleName());

        BiFunction<String, Long, Apple> biFunction = Apple::new;
        System.out.println(biFunction.apply("pink", 2L));

        //三個參數的構造方法,ComplexApple::new,需要自己定義FunctionalInterface
        ThreeParamFuntion<String, Long, String, ComplexApple> threeParamFuntion = ComplexApple::new;
        System.out.println(threeParamFuntion.apply("black", 1L, "blackApple"));

        //再次看下上面list的排序的另一種方法
        List<Apple> list2 = Arrays.asList(new Apple("green", 120), new Apple("abc", 100), new Apple("red", 150));
        list2.sort(Comparator.comparing(Apple::getColor));
        System.out.println(list2);
    }

    private static <T> void useConsumer(Consumer<T> consumer, T t){
        consumer.accept(t);
        consumer.accept(t);
    }

}

打印如下:

hello alex
hello alex
hello today
hello today
[Apple(color=green, weight=120), Apple(color=abc, weight=100), Apple(color=red, weight=150)]
[Apple(color=abc, weight=100), Apple(color=green, weight=120), Apple(color=red, weight=150)]
Apple(color=abc, weight=100)
Apple(color=green, weight=120)
Apple(color=red, weight=150)
-----------------------------------------
Apple(color=abc, weight=100)
Apple(color=green, weight=120)
Apple(color=red, weight=150)
-----------------------------------------
123
i
n
String
Apple(color=pink, weight=2)
ComplexApple(color=black, weight=1, name=blackApple)
[Apple(color=abc, weight=100), Apple(color=green, weight=120), Apple(color=red, weight=150)]

 

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