四大函数式接口
1. Consumer:接收一个输入参数,但不返回任何结果。
import java.util.function.Consumer;
public class ConsumerExample {
public static void main(String[] args) {
// 使用 Consumer 接口打印字符串
Consumer<String> printer = System.out::println;
// 使用 accept 方法处理数据
printer.accept("Hello, Consumer!");
}
}
2. Supplier:不接收任何参数,但返回一个结果。
import java.util.function.Supplier;
public class SupplierExample {
public static void main(String[] args) {
// 使用 Supplier 接口生成随机数
Supplier<Double> randomValue = Math::random;
// 使用 get 方法获取数据
System.out.println("随机数: " + randomValue.get());
}
}
3. Function:接收一个输入参数,并返回一个结果。
import java.util.function.Function;
public class FunctionExample {
public static void main(String[] args) {
// 使用 Function 接口转换字符串为大写
Function<String, String> toUpperCase = String::toUpperCase;
// 使用 apply 方法处理数据
String result = toUpperCase.apply("hello, function!");
System.out.println("转换后的字符串: " + result);
}
}
4. Predicate:接收一个输入参数,并返回一个布尔值结果。
import java.util.function.Predicate;
public class PredicateExample {
public static void main(String[] args) {
// 使用 Predicate 接口判断字符串长度是否大于5
Predicate<String> checkLength = (str) -> str.length() > 5;
// 使用 test 方法检查条件
System.out.println("字符串长度是否大于5: " + checkLength.test("Hello"));
System.out.println("字符串长度是否大于5: " + checkLength.test("Welcome to Java!"));
}
}
增强型函数式接口
1. BiConsumer:接受两个参数并执行操作,没有返回值。
import java.util.function.BiConsumer;
public class BiConsumerExample {
public static void main(String[] args) {
// 使用 BiConsumer 接口处理两个参数
BiConsumer<String, Integer> printKeyValue = (key, value) ->
System.out.println("Key: " + key + ", Value: " + value);
// 使用 accept 方法处理数据
printKeyValue.accept("Java", 8);
}
}
2. BiFunction:接受两个参数并产生一个结果。
import java.util.function.BiFunction;
public class BiFunctionExample {
public static void main(String[] args) {
// 使用 BiFunction 接口组合两个参数
BiFunction<Integer, Integer, Integer> sum = Integer::sum;
// 使用 apply 方法处理数据
System.out.println("Sum: " + sum.apply(5, 3));
}
}
3. UnaryOperator 和 BinaryOperator:是 Function
和 BiFunction
的特殊情况,输入参数和返回结果的类型相同。
import java.util.function.UnaryOperator;
import java.util.function.BinaryOperator;
public class OperatorExample {
public static void main(String[] args) {
// 使用 UnaryOperator 接口对整数进行平方操作
UnaryOperator<Integer> square = (num) -> num * num;
System.out.println("Square: " + square.apply(5));
UnaryOperator<String> toUpperCase = String::toUpperCase;
System.out.println("UpperCase: " + toUpperCase .apply("Hello"));
// 使用 BinaryOperator 接口计算两个整数的最大值
BinaryOperator<Integer> max = Integer::max;
System.out.println("Max: " + max.apply(10, 20));
}
}
4. BiPredicate:接受两个参数并返回布尔值的结果。常用于对两个元素进行比较。
import java.util.function.BiPredicate;
public class BiPredicateExample {
public static void main(String[] args) {
// 使用 BiPredicate 接口判断两个字符串是否相等
BiPredicate<String, String> isEqual = String::equals;
System.out.println("Are equal: " + isEqual.test("hello", "hello"));
}
}