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