Java Lambda

时间:2018-07-02 10:39:33   收藏:0   阅读:219

基础语法

expression = (variable) -> action

函数式接口

四大核心函数式接口:

技术分享图片

消费型接口示例

public static void donation(Integer money, Consumer<Integer> consumer){
    consumer.accept(money);  
}
public static void main(String[] args) {
    donation(1000, money -> System.out.println("好心的麦乐迪为Blade捐赠了"+money+"元")) ;
}

供给型接口示例

public static List<Integer> supply(Integer num, Supplier<Integer> supplier){
       List<Integer> resultList = new ArrayList<Integer>()   ;
       for(int x=0;x<num;x++)  
           resultList.add(supplier.get());
       return resultList ;
}
public static void main(String[] args) {
    List<Integer> list = supply(10,() -> (int)(Math.random()*100));
    list.forEach(System.out::println);
}

函数型接口示例

public static Integer convert(String str, Function<String, Integer> function) {
    return function.apply(str);
}
public static void main(String[] args) {
    Integer value = convert("28", x -> Integer.parseInt(x));
}

断言型接口示例

public static List<String> filter(List<String> fruit, Predicate<String> predicate){
    List<String> f = new ArrayList<>();
    for (String s : fruit) {
        if(predicate.test(s)){
            f.add(s);
        }
    }
    return f;
}
public static void main(String[] args) {
    List<String> fruit = Arrays.asList("香蕉", "哈密瓜", "榴莲", "火龙果", "水蜜桃");
    List<String> newFruit = filter(fruit, (f) -> f.length() == 2);
    System.out.println(newFruit);
}

自定义函数式接口

public class Test2 {
    /*
    一个接口,如果只有一个显式声明的抽象方法,
    那么它就是一个函数接口。
    一般用@FunctionalInterface标注出来(也可以不标)
    */
    interface Inteface1 {
        // 可以不用abstract修饰
        public abstract void test(int x, int y);

        // public void test1();//会报错,不能有两个方法,尽管没有使用abstract修饰
        public boolean equals(Object o);// equals属于Object的方法,所以不会报错
    }

    public static void main(String args[]) {
        Inteface1 f1 = (x, y) -> {
            System.out.println(x + y);
        };
        f1.test(3, 4);
        Inteface1 f2 = (int x, int y) -> {
            System.out.println("Hello Lambda!\t the result is " + (x + y));
        };
        f2.test(3, 4);
    }
}

lambda 表达式和闭包

public static Supplier<Integer> testClosure() {
    int i = 1;
    // i++; // 会报错
    return () -> {
        return i;
    };
}

参考资料

原文:https://www.cnblogs.com/huangwenjie/p/9252116.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!