Java集合类中常用的函数式接口
Java集合类中常用的函数式接口有很多,下面列举了一些常见的函数式接口及其使用方法。
1. Consumer<T>:消费者接口,接收一个泛型T的值,对其进行处理,没有返回值。
Consumer<String> consumer = str -> System.out.println(str);
consumer.accept("Hello"); // 输出: Hello
2. Supplier<T>:供应者接口,返回一个泛型T的值。
Supplier<Integer> supplier = () -> 5;
Integer result = supplier.get(); // 返回: 5
3. Function<T, R>:函数接口,接收一个泛型T的值,返回一个泛型R的值。
Function<String, Integer> function = str -> str.length();
Integer result = function.apply("Hello"); // 返回: 5
4. Predicate<T>:断言接口,接收一个泛型T的值,返回一个boolean值。
Predicate<Integer> predicate = num -> num > 0;
boolean result = predicate.test(5); // 返回: true
5. BiConsumer<T, U>:双参数消费者接口,接收两个泛型T和U的值,对其进行处理,没有返回值。
BiConsumer<Integer, Integer> consumer = (a, b) -> System.out.println(a + b);
consumer.accept(3, 4); // 输出: 7
6. BiFunction<T, U, R>:双参数函数接口,接收两个泛型T和U的值,返回一个泛型R的值。
BiFunction<Integer, Integer, Integer> function = (a, b) -> a + b;
Integer result = function.apply(3, 4); // 返回: 7
7. BiPredicate<T, U>:双参数断言接口,接收两个泛型T和U的值,返回一个boolean值。
BiPredicate<Integer, Integer> predicate = (a, b) -> a > b;
boolean result = predicate.test(4, 3); // 返回: true
8. UnaryOperator<T>:一元操作符接口,接收一个泛型T的值,返回一个泛型T的结果。
UnaryOperator<Integer> operator = num -> num * 2;
Integer result = operator.apply(3); // 返回: 6
9. BinaryOperator<T>:二元操作符接口,接收两个泛型T的值,返回一个泛型T的结果。
BinaryOperator<Integer> operator = (a, b) -> a + b;
Integer result = operator.apply(3, 4); // 返回: 7
以上列举的是一些常用的函数式接口,它们可以用于集合类的处理操作中,如forEach、map、filter等方法。通过使用函数式接口,可以简化代码,并支持Lambda表达式的使用。在实际开发中,函数式接口在集合类的操作中有着广泛的应用。
