Java 8 中函数和谓词的区别
javaobject oriented programmingprogramming更新于 2025/11/13 8:44:17
Java 8 中引入了函数和谓词这两个函数接口,用于在 Java 中实现函数式编程。
函数接口用于进行转换。它可以接受一个参数并产生结果。另一方面,谓词也只能接受一个参数,但它只能返回布尔值。它用于测试条件。
| Sr.不。 | 键 | 函数 | 谓词 |
|---|---|---|---|
| 1 | 基本 | 它可以接受 2 个类型参数,第一个表示输入类型参数类型,第二个表示返回类型。 | 它可以接受一个类型参数,表示输入类型或参数类型。 |
| 2 | 返回类型 | 它可以返回任何类型的值。 | 它只能返回布尔值 |
| 3 | 方法 | 它有抽象方法apply()。 | 它有抽象方法test()。 |
| 4. | 用例 | 它可用于实现条件检查 | 它可用于转换和返回值。 |
示例谓词
public class Main {
public static void main(String args[]) {
List<Integer> numList = new ArrayList<>();
numList.add(5);
numList.add(10);
Predicate<Integer> pred = i -> i > 5;
numList.stream().filter(pred).forEach(i -> System.out.println(i));
}
}
Example of Function
public class Main {
public static void main(String args[]) {
List<Integer> numList = new ArrayList<>();
numList.add(78);
numList.add(10);
Function<Integer, Integer> fun = i -> i / 2;
numList.stream().map(fun).forEach(System.out::println);
}
}
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

