所有标注了@FunctionalInterface注解的接口都是函数式接口
Function 介绍
Java 8引入了一个新的函数式接口Function。Function接口接收一个参数,并返回一个结果。它定义了一个apply()方法,用于对输入参数进行转换操作。
Function接口有以下两个重要的方法:
- R apply(T t):接收一个参数t,返回一个结果R。
- default Function<T, V> andThen(Function<? super R, ? extends V> after):返回一个先应用当前Function对象然后应用after对象的新的Function对象。
Function接口可用于定义lambda表达式或方法引用,可以作为参数传递给其他函数或方法。
下面是一个使用Function接口的例子,将字符串转换为整数:
Function<String, Integer> toInt = Integer::parseInt;
Integer number = toInt.apply("123");
System.out.println(number); // 输出123
在这个例子中,我们创建了一个Function对象toInt,将字符串转换为整数。然后,我们调用toInt对象的apply()方法,将字符串"123"作为参数传递进去,并得到了一个整数结果。
除了使用方法引用,我们还可以使用lambda表达式来定义Function接口。
Function<Integer, String> toString = (n) -> String.valueOf(n);
String str = toString.apply(123);
System.out.println(str); // 输出"123"
在这个例子中,我们创建了一个Function对象toString,将整数转换为字符串。然后,我们调用toString对象的apply()方法,将整数123作为参数传递进去,并得到了一个字符串结果。
通过使用Function接口,我们可以将操作封装到一个对象中,并传递给其他方法或函数,从而实现更灵活和可组合的代码。
Function 使用
public void test(){
Function<Integer,Integer> test1=i->i+1;
Function<Integer,Integer> test2=i->i*i;
System.out.println(calculate(test1,5));
System.out.println(calculate(test2,5));
}
public static Integer calculate(Function<Integer,Integer> test,Integer number){
return test.apply(number);
}
/** print:6*/
/** print:25*/
自定义Function
@FunctionalInterface
public interface BufferedReaderProcessor {
String process(BufferedReader b) throws IOException;
}
public class BufferedReaderProcessorTest {
public static String processFile(BufferedReaderProcessor p) throws
IOException {
try (BufferedReader br =
new BufferedReader(new FileReader("d://aaa.txt"))) {
return p.process(br);
}
}
public static void main(String[] args) throws IOException {
String oneLine =
processFile((BufferedReader br) -> br.readLine());
System.out.println(oneLine);
String twoLines =
processFile((BufferedReader br) -> br.readLine() + br.readLine());
System.out.println(twoLines);
}
}
自定义类Function关键字
如果你需要定义一个Lambda,将输入对象的信息映射到输出,就可以使用这个接口(比如把字符串映射为它的长度)。在下面的代码中,我们向你展示如何利用它来创建一个map方法,以将一个String列表映射到包含每个String长度的Integer列表。
public class FunctionTest {
@FunctionalInterface
public interface FunctionDemo<T, R> {
R fire(T t);
}
public static <T, R> List<R> map(List<T> list,
FunctionDemo<T, R> f) {
List<R> result = new ArrayList<>();
for (T s : list) {
result.add(f.fire(s));
}
return result;
}
public static void main(String[] args) {
// [7, 2, 6]
List<Integer> l = map(Arrays.asList("lambdas", "in", "action"), (String s) -> s.length());
System.out.println(l);
}
}