Java8::函数式接口

Java8::函数式接口

一、简介

1.1 四大核心函数

接口入参类型返参类型描述描述
Consumer <T> 消费型接口Tvoid有入参无出参对类型为T的对象应用操作,包含方法:void accept(T t)
Supplier <T> 供给型接口T有出参无入参返回类型为T的对象,包含方法:T get()
Function <T, R> 函数型接口TR有出参有入参对类型为T的对象应用操作,并返回结果。结果是R类型的对象。包含方法:R apply(T t)
Predicate<T> 断定型接口Tboolean入参T,返回Boolean确定类型为T的对象是否满足某约束,并返回boolean 值。包含方法:boolean test(T t)
BiFunction<T, U, R>T, UR入参T、U,反参R对类型为 T, U 参数应用操作,返回 R 类型的结果。包含方法为: R apply(T t, U u);

1.2 其他函数

接口入参类型返参类型描述描述
BiFunction<T, U, R>T, UR入参T、U,反参R对类型为 T, U 参数应用操作,返回 R 类型的结果。包含方法为: R apply(T t, U u);

二、举例

2.1 Consumer接口

Consumer<String> consumer = (String str) -> System.out.println(str);
consumer.accept("hello world!");// hello world!

2.2 Supplier 接口

public static void main(String[] args) {
        int[]arr={20,12,3,6,8};
        Supplier supplier = ()->{
            int m=arr[0];
            for(int i=0;i<arr.length;i++){
                if(arr[i]>m){
                    m=arr[i];
                }
            }
            return m;
        };
        System.out.println(supplier.get());// 20
        System.out.println(getMax(supplier));// 20
    }

    /**
     * 返回最大值
     * @param sup
     * @return
     */
    public static Integer getMax(Supplier<Integer>sup) {
        return sup.get();
    }

2.3 Function接口

  public static void main(String[] args) {
        Function<String,Integer> function = (a)-> Integer.valueOf(a);
        System.out.println(function.apply("17"));// 17
        System.out.println(getInteger(function,"17")); // 17
    }

    /**
     * 字符串转数字
     * @param fun
     * @return
     */
    public static Integer getInteger(Function<String,Integer> fun,String str) {
        return fun.apply(str);
    }

2.4 Predicate接口

 Predicate<Integer> predicate = number -> number != 0;
 System.out.println(predicate.test(10));    //true

2.5 BiFunction接口

 BiFunction<String,String,Integer> biFunction = (String a,String b)-> Integer.valueOf(a) + Integer.valueOf(b);
 System.out.println(biFunction.apply("12","3")); // 15

参考链接:https://www.cnblogs.com/konglxblog/p/16456680.html


版权声明:本文为qq_29898779原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。