Java8新特性—四大内置函数式接口( 二 )

执行结果
010011空的hello world!9632从上面的栗子我们可以看出:
Java把这些映射规则,也就是y = f(x)中的【f】抽象成了这个Function接口的apply逻辑 。然后x和y,自变量和因变量,也就是入参出参,Java使用了扩展性更强的泛型参数类型,而不是固定Object入参出参 。因为固定Object的话还要涉及到类型转换,还有可能报ClassCast异常,很麻烦
再看一个栗子:
/** * @author vchicken * @version 1.0 * @description FunctionTest * @date 2022/11/10 12:10:06 */public class FunctionTest<T,R> {public static void main(String[] args) {FunctionTest<Integer, Integer> functionTest1 = new FunctionTest<>();System.out.println(functionTest1.functionTest(null, s -> s == null ? 0 : s));System.out.println(functionTest1.functionTest(100, s -> s == null ? 0 : s));System.out.println(functionTest1.functionTest(10, s -> s + 1));FunctionTest<String, String> functionTest2 = new FunctionTest<>();System.out.println(functionTest2.functionTest(null, s -> s == null ? "空的" : s));System.out.println(functionTest2.functionTest("hello world!", s -> s == null ? "空的" : s));}public R functionTest(T in,Function<T,R> function){return function.apply(in);}}执行结果:
010011空的hello world!【Java8新特性—四大内置函数式接口】结合两个栗子我们可以看出来:

我们可以使用Function接口来将同一个方法的处理逻辑抽象出来,在调用方法的时候,将处理逻辑以Lambda表达式的形式传入,实现同一个方法可以处理不同的代码逻辑,而且使用泛型来表示方法的出入参,可以避免不必要的类型转换和异常发生 。@vchicken
Function接口在JDK中的应用在JDK1.8中的新属性Stream中,就使用到了Function接口,看下面的源码:
Java8新特性—四大内置函数式接口

文章插图
通过一个例子来看看怎样使用map这个接口
public static void main(String[] args) {Stream<Integer> stream = Stream.of(-1,0,1,2,3,4);Stream<Integer> stream1 = stream.map(integer -> integer + 1);stream1.forEach(System.out::println);}执行结果:
012345案例:将数组中的数,依次平方,等到一个一个新的数组
List<Integer> myList = new ArrayList<>();myList.add(-2);myList.add(0);myList.add(1);myList.add(3);myList.add(5);myList.add(7);List<Integer> collect = myList.stream().map(integer -> integer*integer).collect(Collectors.toList());collect.forEach(System.out::println);执行结果:
401925492.Consumer接口什么是Consumer接口?
Java8新特性—四大内置函数式接口

文章插图
从源码可以看出,Consumer与Function类似,只有一个accept抽象方法待实现,只不过唯一的区别是,Consumer的accept使用void修饰,没有返回值,而Function有返回值 。
Consumer接口又称为消费型接口,顾名思义,入参传入后,被accept方法消费掉了,什么都没得到 。
举个栗子:
public static void main(String[] args) {Consumer<Object> consumer1 = new Consumer<Object>() {@Overridepublic void accept(Object o) {System.out.println("这次消费了:" + o.toString());}};consumer1.accept("100w元在双十一!这下穷死了!");Consumer<String> consumer2 = s -> System.out.println("这次消费了:" + s);consumer2.accept("120w元在双十二!又穷死了!");}执行结果:
这次消费了:100w元在双十一!这下穷死了!这次消费了:120w元在双十二!又穷死了!同样的,我们可以提取公共方法为:
/** * @author vchicken * @version 1.0 * @description ComsumerTest * @date 2022/11/10 17:14:11 */public class ConsumerTest<T> {public static void main(String[] args) {ConsumerTest<String> consumerTest = new ConsumerTest<>();consumerTest.accept("100w元在双十一!这下穷死了!", s -> System.out.println("这次消费了:" + s));consumerTest.accept("120w元在双十二!又穷死了!", s -> System.out.println("这次消费了:" + s));}public void accept(T in, Consumer<? super T> consumer) {consumer.accept(in);}}

经验总结扩展阅读