四大函数式接口


函数型接口(function)

作用:传入什么,就输出什么
源码

@FunctionalInterface
public interface Function {
    R apply(T t);
}

使用

package com.luoKing.funcation;

import java.util.function.Function;

public class function {

    public static void main(String[] args) {
//        Function function = new Function() {
//            @Override
//            public String apply(String s) {
//                return s;
//            }
//        };
        Function function = (str)->{
            return str;
        };


        System.out.println(function.apply("asd"));
    }
}

断点型接口

输入类型可以自定义,输出类型只能为boolon
源码

@FunctionalInterface
public interface Predicate {
    boolean test(T t);

测试

package com.luoKing.funcation;

import java.util.function.Predicate;

public class predicae {

    public static void main(String[] args) {
//        Predicate predicate = new Predicate() {
//            @Override
//            public boolean test(String s) {
//                return s.isEmpty();//判断字符串是否为空
//            }
//        };

        Predicate predicate = (str)->{
            return str.isEmpty();
        };
        System.out.println(predicate.test("qwe"));
    }
}

消费型接口(consumer)

作用:只接受参数,不返回参数
源码

@FunctionalInterface
public interface Consumer {
    void accept(T t);

实列

package com.luoKing.funcation;

import java.util.function.Consumer;

public class consumer {

    public static void main(String[] args) {
//        Consumer consumer = new Consumer() {
//            @Override
//            public void accept(String s) {
//                System.out.println("hello,???");
//            }
//        };
        
        Consumer consumer = (String s)->{ System.out.println("hello,???");};
        consumer.accept("sdadsasd");

    }
}

供给者接口

不输入参数,只输出参数
源码


@FunctionalInterface
public interface Supplier {
    T get();
}

实例

package com.luoKing.funcation;

import java.util.function.Supplier;

public class supplier {

    public static void main(String[] args) {
//        Supplier supplier = new Supplier<>() {
//            @Override
//            public String get() {
//                return "hello,???";
//            }
//        };



        Supplier supplier = ()->{return "hello,???";};

        System.out.println(supplier.get());

    }

}

为什么要使用这四大函数式接口?

  1. 简化编程模型
  2. 在新版本的底层中大量应用

相关