
Java 函数式接口的可用的方法
函数式接口是一种只包含一个抽象方法的接口。Java 提供了几个预定义的函数式接口,用于常见操作,例如谓词、函数和消费。
常用的方法
以下是如何使用 Predicate、Function 和 Consumer 函数式接口一些常见方法的示例:
Predicate:
立即学习“Java免费学习笔记(深入)”;
-
test(T t): 返回一个布尔值,表示该函数式接口上应用的对象是否符合条件。
Function:
-
apply(T t): 返回一个值,表示将该函数式接口应用于对象的结果。 -
compose(Function<u t> before)</u>: 返回一个新的函数式接口,它先调用before并将结果应用于apply。 -
andThen(Function<t u> after)</t>: 返回一个新的函数式接口,它先调用apply,然后将结果应用于after。
Consumer:
-
accept(T t): 对一个对象执行操作,但没有返回值。
实战案例
Predicate:
立即学习“Java免费学习笔记(深入)”;
Predicate<String> isPalindrome = string -> string.equalsIgnoreCase(new StringBuilder(string).reverse().toString());
List<String> words = List.of("apple", "kayak", "banana", "racecar");
List<String> palindromes = words.stream()
.filter(isPalindrome)
.toList();
System.out.println(palindromes); // [apple, kayak, racecar]Function:
Function<Integer, Integer> square = number -> number * number;
List<Integer> numbers = List.of(1, 2, 3, 4, 5);
List<Integer> squares = numbers.stream()
.map(square)
.toList();
System.out.println(squares); // [1, 4, 9, 16, 25]Consumer:
Consumer<String> print = string -> System.out.println(string);
List<String> words = List.of("Hello", "World", "Java");
words.forEach(print);
// 输出:
// Hello
// World
// Java


















