JAVA8 函数式接口举例

文章展示了Java中Function、Predicate、Supplier和Consumer接口的使用示例,包括apply、test、get和accept等方法,以及lambda表达式和方法引用的应用,强调了这些接口在处理函数式编程时的作用。
摘要由CSDN通过智能技术生成
public class FunctionDemo {

    public static Integer testApply(Function<String,Integer> function , String str){
        Integer i = function.apply(str);
        return i;
    }

    public static Double testApply(Function<Integer,String> function1 ,Function<String,Double> function2, Integer i){
        return function1.andThen(function2).apply(i);
    }

    public static void main(String[] args) {
        testApply(t -> Integer.valueOf(t) , "123");
    }
}
public class PredicateDemo {

    public static boolean testPredicate(Predicate<Integer> function, String str) {
        return function.test(Integer.valueOf(str));
    }

    public static void main(String[] args) {
        testPredicate(t -> t > 1, "123");
    }
}
public class SupplierDemo {


    public static Integer testSupplierGet(Supplier<Integer> function){
        return function.get();
    }

    public static void main(String[] args) {
        String x = "123";
        testSupplierGet(new Supplier<Integer>() {
            @Override
            public Integer get() {
                return Integer.valueOf(x);
            }
        });
        testSupplierGet(() ->Integer.valueOf(x));
    }
}
public class ConsumerDemo {


    public static void testAccept(Consumer<P> function, P p) {
        function.accept(p);
    }

    public static void main(String[] args) {
        P p = new P();
        p.setAge(1);
        testAccept(new Consumer<P>() {
            @Override
            public void accept(P p) {
                p.setAge(123);
                System.out.println(p.getAge());
            }
        }, p);

        System.out.println(p.getAge());

        Integer i = 10;
        testAccept2(new Consumer<Integer>() {
            @Override
            public void accept(Integer integer) {
                System.out.println(integer);
                integer = 100;//引用指向对象,对象变了
                System.out.println(integer);
            }
        }, i);

        System.out.println(i);//


        String str = "10";
        testAccept3(new Consumer<String>() {
            @Override
            public void accept(String str) {
                System.out.println(str);
                str = "100";
                System.out.println(str);
            }
        }, str);

        System.out.println(str);
    }

    public static void testAccept2(Consumer<Integer> function, Integer x) {
        function.accept(x);
    }

    public static void testAccept3(Consumer<String> function, String x) {
        function.accept(x);
    }


    @Data
    @NoArgsConstructor
    public static class P {
        private int age;

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值