暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Java新特性解读JDK8之函数式接口Function

227decision 2020-01-11
2147

上一篇文章介绍了自定义Lambda接口,使用Lambda表达式必须要先自定义函数式接口,这样不方便;jdk8内置了许多函数式接口提供我们使用,基本上不需要再定义新的函数式接口。

jdk8内置了四大核心函数式接口:Consumer<T>,Supplier<T>,Function<T, R>,Predicate<T>。

首先介绍Function<T, R>,T:入参类型,R:返回类型,源码如下:

    package java.util.function;
    import java.util.Objects;
    /**
    * Represents a function that accepts one argument and produces a result.
    *
    * <p>This is a <a href="package-summary.html">functional interface</a>
    * whose functional method is {@link #apply(Object)}.
    *
    * @param <T> the type of the input to the function
    * @param <R> the type of the result of the function
    *
    * @since 1.8
    */
    @FunctionalInterface
    public interface Function<T, R> {
    /**
    * Applies this function to the given argument.
    *
    * @param t the function argument
    * @return the function result
    */
    R apply(T t);
    }

    Function使用

      package com.example.functionalinterfacedemo;
      import java.util.function.Function;
      public class FunctionDemo implements Function<Object, Object>{
      /**
      *自定义 实现Function接口,重写方法apply()
      *仅作介绍方便理解,不作为常规使用方式
      */
      @Override
      public Object apply(Object t) {
      return t+",function apply()处理后";
      }

      public static void main(String[] args) {
          System.out.println(new FunctionDemo().apply("test"));
      //常规使用
      Function<Integer, Integer> function=input->input*10;
      System.out.println(function.apply(10));
      }
      }



      最后修改时间:2020-07-01 13:37:32
      文章转载自227decision,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

      评论