菜鸟为了学习所写
目录
一、Function接口
此接口定义了一个apply 方法,它接收一个T 类型的对象,返回一个 R 类型的对象:
1、示例(Function示例)
private static void useFunctionInterface() {
//将一个英文句子按空格分割,然后统计得到的单词的个数
Function<String, Integer> wordCount =
s -> s.split(" ").length;
String str = "this is a test.";
System.out.println(wordCount.apply(str));//4
}
-
split
是String
类的一个方法,用于将字符串按指定的正则表达式分割。 -
参数
" "
表示空格(正则表达式),意味着每当遇到一个空格时,就将字符串分割成新的部分。 -
返回值是一个
String
数组,每个元素都是一个单词。
split(" ")
会将字符串 s
中的每个单词提取出来,存放在一个数组中。
例如
String str = "this is a test.";
String[] words = str.split(" ");
输出words
["this", "is", "a", "test."]
所以在Function示例里面的apply()输入s,输出的是s.split(" ")这个数组的长度。
二、BiFuntion接口
作为Function 接口的特例, 有一个 BiFunction <T, U, R>接口 ,它所定义的 apply 方法接收 两个参数: T 和 U 类型的,然后返回一个 R 类型 的对象。
2、示例(BiFunction接口)
private static void useBiFunctionInterface() {
//检查某字符串是否长度超限
BiFunction<String, Integer, Boolean> exceedsMaxLength =
(s, maxLength) -> {
int actualLength = s.length();
return actualLength > maxLength;
};
Scanner scanner = new Scanner(System.in);
System.out.println("输入一个最多8个字符的字符串");
String userInput = scanner.nextLine();
//检查数据是否有效
boolean result = exceedsMaxLength.apply(userInput, 8);
if (!result) {
System.out.println("符合要求");
} else {
System.out.println("无效输入");
}
}
这是BiFunction接口的示例。
三、UnaryOperator接口
UnaryOperator接口派生自Function 接口,它的返回值类型与参数类型一致,其实就是 Function<T,T> 的简写。
3、示例 (UnaryOperator接口)
private static void useUnaryOperator() {
//接收一个参数,返回同类型的单个结果
UnaryOperator<Integer> autoIncrease = num -> ++num;
System.out.println(autoIncrease.apply(100));
}
四、BinaryOperator接口
该接口在使用时,传入两个参数,然后传出一个和传入的参数一样类型的参数。
4、示例(BinaryOperator接口)
private static void useBinaryOperator() {
//接收两个参数,返回单个结果,三个都是同类型的
BinaryOperator<Integer> add = (x, y) -> x + y;
var sum = add.apply(100, 200);
System.out.println(sum);//300
//BinaryOperator定义了两个静态方法,可以用于求两个数值的最大值或最小值
Comparator<Integer> comparator = Integer::compareTo;
BinaryOperator<Integer> maxBy = BinaryOperator.maxBy(comparator);
System.out.println(maxBy.apply(100, 200));//200
}