说明
这里只探究稍微特殊点的两个函数式接口:UnaryOperator
和 BinaryOperator
UnaryOperator<T>
对类型为 T 参数应用操作,进行一元运算并返回 T 类型的结果
@FunctionalInterface
public interface UnaryOperator<T> extends Function<T, T> {
/** a function that always returns its input argument */
static <T> UnaryOperator<T> identity() {
return t -> t;
}
}
样例
探究 identity
方法
代码
public class TestDemo {
/** 测试 */
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
Stream<LocalDateTime> stream = Stream.of(now, now.plusDays(1L), now.plusDays(2L));
List<LocalDateTime> collect = stream.map(UnaryOperator.identity()).collect(Collectors.toList());
collect.forEach(System.out::println);
}
}
输出
2021-12-30T17:12:34.273
2021-12-31T17:12:34.273
2022-01-01T17:12:34.273
BinaryOperator<T>
对类型为 T 参数应用操作,进行二元运算并返回 T 类型的结果
@FunctionalInterface
public interface BinaryOperator<T> extends BiFunction<T,T,T> {
public static <T> BinaryOperator<T> minBy(Comparator<? super T> comparator) {
Objects.requireNonNull(comparator);
return (a, b) -> comparator.compare(a, b) <= 0 ? a : b;
}
public static <T> BinaryOperator<T> maxBy(Comparator<? super T> comparator) {
Objects.requireNonNull(comparator);
return (a, b) -> comparator.compare(a, b) >= 0 ? a : b;
}
}
样例
探究 maxBy
和 minBy
方法
代码
public class TestDemo {
/** 测试 */
public static void main(String[] args) {
int[] arr1 = {9, 1, 7, 3, 5};
Integer maxResult = arr1[0];
Integer minResult = arr1[0];
for(int i = 1; i < arr1.length; i ++){
maxResult = getMaxInt(maxResult, arr1[i], Integer::compareTo);
minResult = getMinInt(minResult, arr1[i], Integer::compareTo);
}
System.out.println("最大值: " + maxResult);
System.out.println("最小值: " + minResult);
}
/** 定义操作方法:获取最大值 */
public static int getMaxInt(int a, int b, Comparator<Integer> comparator){
return BinaryOperator.maxBy(comparator).apply(a, b);
}
/** 定义操作方法:获取最小值 */
public static int getMinInt(int a, int b, Comparator<Integer> comparator){
return BinaryOperator.minBy(comparator).apply(a, b);
}
}
输出
最大值: 9
最小值: 1