Java新特性解读JDK8之函数式接口Function
上一篇文章介绍了自定义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*/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()*仅作介绍方便理解,不作为常规使用方式*/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));}}
