首页 > 编程语言 > 详细

Java1.8新特性 - Java内置的四大核心函数式接口

时间:2019-10-26 17:42:35      阅读:89      评论:0      收藏:0      [点我收藏+]

Java内置的四大核心函数式接口

Consumer:消费型接口

对类型为T的对象应用操作,包含方法:void accept(T t)

public class TestLambda02 {
    public static void main(String[] args) {
        testConsumer(9999, (x) -> {
           System.out.println("打游戏花费:" + x);
        });
    }

    public static void testConsumer(double money, Consumer<Double> consumer) {
        consumer.accept(money);
    }
}

Supplier:供给型接口

返回包含类型为T的对象,包含方法:T get()

public class TestLambda02 {
    public static void main(String[] args) {
        List<Integer> list = testSupplier(10, () -> (int)(Math.random() * 100));
        list.forEach(System.out::println);
    }

    public static List<Integer> testSupplier(int num, Supplier<Integer> supplier) {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < num; i ++) {
            Integer n = supplier.get();
            list.add(n);
        }
        return list;
    }
}

Function<T, R>:函数型接口

对类型为T的对象应用操作,并返回结果,结果类型为R。包含方法:R apply(T t)

public class TestLambda02 {
    public static void main(String[] args) {
        String string = testFunction("哈哈哈哈哈哈哈", (str) -> str.substring(0, str.length() - 2));
        System.out.println("---->" + string);
    }

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

Predicate(T):断定型接口

确定类型为T的对象是否满足某约束,并返回boolean值。包含方法:boolean test(T t)

public class TestLambda02 {
    public static void main(String[] args) {
        System.out.println(testPredicate("哈哈哈哈皇后", (str) -> str.length() == 3));
    }

    public static boolean testPredicate(String string, Predicate<String> predicate) {
        return predicate.test(string);
    }
}

PS:除了这四个接口,java还内置了其他很多接口,这里不再赘述。可以在rt.jar文件下的java/util/function包下查看。

Java1.8新特性 - Java内置的四大核心函数式接口

原文:https://www.cnblogs.com/fx-blog/p/11743909.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!