说说Java8中的几个函数式接口

JAVA8中的函数式接口 Function、Supplier、Predicate、Consumer

这几个接口在Java8中已经定义好,因为每个接口基本主要就有一个接口方法所以其实完全可以自己通过@FunctionalInterface自己定义使用,不过人家给你定义好了而且一般java8这些接口里面除了主要接口方法外还有几个default方法,所以很多时候我们直接用会更方便一些。

Predicate接口 (判断满足某个特定条件,test方法)

public class AppleFilter {

    public static List<Apple> filterApples(List<Apple> inventory, Predicate<Apple> p) {
        List<Apple> result = new ArrayList<>();
        for(Apple apple : inventory) {
            if(p.test(apple)) {
                result.add(apple);
            }
        }
        return result;
    }


    public static void main(String[] args) {
        List<Apple> inventory = new ArrayList<>();
        // ... 省略添加苹果的操作
        inventory.add(new Apple(120, "green"));
        inventory.add(new Apple(90, "red"));
        filterApples(inventory, Apple::isGreenApple);
        filterApples(inventory, Apple::isHeavyApple);
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    private static class Apple {
        int weight;
        String color;

        public static boolean isGreenApple(Apple apple) {
            return "green".equals(apple.getColor());
        }

        public static boolean isHeavyApple(Apple apple) {
            return apple.getWeight()>100;
        }
    }
}

Consumer接口 (对传入对参数对象进行某些操作,accept方法)

public class LamdaLearn {

    // consumer
    public static <T> void forEach(List<T> list, Consumer<T> c) {
        for(T i : list){
            c.accept(i);
        }
    }



    public static void main(String[] args) {
        // consumer
        forEach(Arrays.asList(1,2,3,4), (Integer i) -> System.out.println(i));

    }

}

Function接口 (对传入对象进行映射,返回一个泛型对象, apply方法)

public class Test {  
    public static void main(String[] args) throws InterruptedException {  
        String name = "";  
        String name1 = "12345";  
        System.out.println(validInput(name, inputStr -> inputStr.isEmpty() ? "名字不能为空":inputStr));  
        System.out.println(validInput(name1, inputStr -> inputStr.length() > 3 ? "名字过长":inputStr));  
    }  

    public static String validInput(String name,Function<String,String> function) {  
        return function.apply(name);  
    }  
} 

Supplier接口 (供给工作,get方法)

public class LamdaLearn {

    public static void main(String[] args) {
        //实例化
        Supplier<AppleFilter> filterSupplier = AppleFilter::new;
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值