进阶day06-常用的函数式接口-Function(转换工厂)

This commit is contained in:
2026-03-14 13:16:23 +08:00
parent 50eb7dcb2c
commit c2452d0811

View File

@@ -0,0 +1,37 @@
package com.inmind.functional_interface02;
import java.util.function.Function;
/*
学习的内容:
6.常用的函数式接口-FunctionFunction就是一个数据工厂用来进行数据转换
Interface Function<T,R>
参数类型
T - 原料的类型 - 参数
R - 产品的类型 - 返回值
抽象方法:
R apply(T t):表示进T类型的数据转换成R类型的数据
默认方法:
default <V> Function<T,V> andThen(Function after) 合并2个Function接口生成一个新的先执行this的apply方法再执行after的apply方法
default <V> Function<V,R> compose(Function before) 与以上的方法完全相反
需求:"100"->100
*/
public class Demo13 {
public static void main(String[] args) {
// method(str->Integer.parseInt(str),"100");
// method((String str)->{return Integer.parseInt(str);},"100");
//----------------------------------也可以这么做-----------------------------
//定义一个转换工厂
Function<String,Integer> function = str->Integer.parseInt(str);//接口的多态
Integer result = function.apply("10");
System.out.println(result);
}
//定义出一个方法接收的是一个数据工厂String->Integer,字符串参数,没有返回值
public static void method(Function<String,Integer>function,String str) {
Integer result = function.apply(str);
System.out.println(result);
}
}