这时我们可以利用Java 8的Function接口来消灭if...else...。
publicstaticvoidmain(String[] args){ Function<Integer, Integer> plus = i -> i +1; Function<Integer, Integer> mult = i -> i * i; System.out.println("F1:"+ plus.apply(1));// 结果2System.out.println("F2:"+ mult.compose(plus).apply(3));// 等于mult.apply(plus.apply(2)), 结...
// Function 接口的泛型,第一个参数是入参类型,第二个参数是出参类型// Function 接口只有一个抽象方法,就是 apply(),下面利用 Lambda 表达式实现这个抽象方法并创建 Function 对象Function<Integer, String> function = num ->"GTA"+ num;// 将5这个参数传递给function,得到返回结果Stringresult=function.apply(...
int stringLength = length.apply("Sample"); int listSize = size.apply(Arrays.asList("Java", "Function", "apply")); // stringLength的结果为6,listSize的结果为3 通过使用Function接口中的apply方法,我们能以一种更函数化的风格编写Java程序。这不仅提高了代码的可读性,而且增强了可维护性。通过编写清...
java.util.function.Function<T,R>接口用来根据一个类型的数据得到另一个类型的数据, 前者称为前置条件,后者称为后置条件。 Function接口中最主要的抽象方法为:R apply(T t),根据类型T的参数获取类型R的结果。 使用的场景例如:将String类型转换为Integer类型。
Rapply(Tt) Applies this function to the given argument. default <V>Function<V,R>compose(Function<? super V,? extendsT> before) Returns a composed function that first applies thebeforefunction to its input, and then applies this function to the result. ...
return function1.compose(function2).apply(num);}/*** 使用andThen函数,简单的说,就是从左向右处理。** @param num 变量* @param function1 函数1* @param function2 函数2* @returnInteger*/private Integer computeForAndThen(Integer num,Function<Integer, Integer> function1,...
Tutorial explains the in-built functional interface Function<T, R> introduced in Java 8. It uses examples to show how the apply(), andThen(), compose() & identity() methods of the Function interface are to be used. What is java.util.function.Function Function<T, R> is an in-built...
代码语言:javascript 复制 // Use the City's method references and assign them to functionsFunction<City,String>getNameFunction=City::getName;Function<City,String>getCodeFunction=City::getCode;System.out.println("The code for "+getNameFunction.apply(sf)+" is "+getCodeFunction.apply(sf));->Th...
意义Function 是 Java 8 引入的一个函数式接口,位于 java.util.function 包中。它的主要作用是定义一个从类型 T 到类型 R 的函数映射。具体来说,它包含一个抽象方法 apply(T t),该方法接受一个参数 t 并返回一个结果 R。 泛型参数:T:输入参数的类型。R:输出结果的... ...