四大函数式接口

函数型接口(function)

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

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

使用

package com.luoKing.funcation;

import java.util.function.Function;

public class function {

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


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

断点型接口

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

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

测试

package com.luoKing.funcation;

import java.util.function.Predicate;

public class predicae {

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

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

消费型接口(consumer)

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

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

实列

package com.luoKing.funcation;

import java.util.function.Consumer;

public class consumer {

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

    }
}

供给者接口

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


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

实例

package com.luoKing.funcation;

import java.util.function.Supplier;

public class supplier {

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



        Supplier<String> supplier = ()->{return "hello,🙅‍";};

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

    }

}

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

  1. 简化编程模型
  2. 在新版本的底层中大量应用
posted @ 2022-05-07 15:58  小罗要有出息  阅读(42)  评论(0编辑  收藏  举报