欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

函数式接口的用途(Function、Predicate、Consumer、Supplier)

程序员文章站 2022-06-13 13:51:02
...

 函数式接口的用途(Function、Predicate、Consumer、Supplier)

package main.test;

import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * @Auther: wdq
 * @Date: 2020/4/21 16:18
 * @Description:
 */
public class FunctionInterfaceDemo {
    public static void main(String[] args) {
        /* Function<T,R> 输入参数类型自定义,返回值类型自定义
        Function<String,String> function = new Function<String, String> () {
            @Override
            public String apply(String s) {
                return null;
            }
        };
         */
        Function<String,String> function = s -> s;
        System.out.println(function.apply("Function"));

        /* Predicate<T> 输入参数类型自定义,返回值类型为Boolean
        Predicate<String> predicate = new Predicate<String>() {
            @Override
            public boolean test(String s) {
                return false;
            }
        };
         */
        Predicate<String> predicate = s -> s.isEmpty();
        System.out.println(predicate.test("Predicate"));

        /* Consumer<T> 输入参数类型自定义,返回值类型是void
        Consumer<String> consumer = new Consumer<String>() {
            @Override
            public void accept(String s) {

            }
        };
         */
        Consumer<String> consumer = s -> System.out.println(s);
        consumer.accept("Consumer");

        /* Supplier<T> 无参数类型,返回值类型为T(自定义)
        Supplier<String> supplier = new Supplier<String>() {
            @Override
            public String get() {
                return null;
            }
        };
         */
        Supplier<String> supplier = () -> "Supplier";
        System.out.println(supplier.get());
    }

}

 

相关标签: JAVA面试题