Java8-Function(二)

641 阅读2分钟

这是我参与8月更文挑战的第19天,活动详情查看:8月更文挑战

二、Function

rt.jar -> package java.util.function

1. 始祖父类

总结来说,包内的其他方法均由下列的父类演变、扩展而成

(1)Function<T,R>
  1. 单个入参,T为入参的类型,R为返回值的类型。
  2. 支持链式关联上游 Function<V,T>,即 Function<V,T> 执行完毕后,再执行 Function<T,R>。
  3. 支持链式关联下游 Function<R,V>,即 Function<T, R> 执行完毕后,再执行 Function<R,V> 。
  4. 返回值为基础类型的扩展类:ToIntFunction、ToLongFunction、ToDoubleFunction。
  5. 入参及返回值均为基础类型的扩展类:IntToDoubleFunction、IntToLongFunction、LongToIntFunction、LongToDoubleFunction、DoubleToIntFunction、DoubleToLongFunction。
(2)BiFunction<T,U,R>
  1. 两个入参,一个返回值(废话,所有Java方法都是一个返回值)。
  2. 支持链式关联下游 Function<R,V>,即 BiFunction<T, U, R> 执行完毕后,再执行 Function<R,V> 。
  3. 返回值为基础类型的扩展类:ToIntBiFunction、ToLongBiFunction、ToDoubleBiFunction。

2. 无返回值型

(1)Consumer<T>
  1. 传入一个参数,相当于返回值为 void 的 Function<T, Void>。
  2. 返回值为基础类型的扩展类:IntConsumer、LongConsumer、DoubleConsumer。
Consumer<Integer> printInt = System.out::println;
// 实际引用的是 System.out 的方法 void println(Object x)

Consumer<String> printString = System.out::println;
// 实际引用的是 System.out 的方法 void println(String x)
(2)BiConsumer<T, U>
  1. 传入两个参数(可以不同类型),相当于返回值为 void 的 BiFunction<T, U, Void>。
  2. 返回值为基础类型的扩展类:ObjIntConsumer、ObjLongConsumer、ObjDoubleConsumer。
// 实现简单的累加器
BiConsumer<AtomicInteger, Integer> addFunc = (ato, number) -> {
    ato.addAndGet(number);
};
// 或简写成
// BiConsumer<AtomicInteger, Integer> accumulator = AtomicInteger::addAndGet;

AtomicInteger accumulator = new AtomicInteger(0);
// 并发累加
Stream.iterate(0, x -> x + 1).limit(10).parallel().forEach(x -> addFunc.accept(accumulator, x));
System.out.println(accumulator.get());
/* 输出:
45
*/

3. 无入参型

(1)Supplier<T>

返回值为基础类型的扩展类:IntSupplier、LongSupplier、DoubleSupplier、BooleanSupplier。

Random random = new Random(System.currentTimeMillis());
Supplier<Integer> createNumber = random::nextInt;
for (int i = 0; i < 10; i++) {
    System.out.println(createNumber.get());
}
(2)BiSupplier<T, U>

想什么呢,没有这个类。

4. 出入参类型一致型

(1)UnaryOperator<T>
  1. 单个入参,在 List.replaceAll 及 Venctor、AtomicReference、AtomicReferenceArray 的方法中有被用作入参。
  2. 返回值为基础类型的扩展类:IntUnaryOperator、LongUnaryOperator、DoubleUnaryOperator。
(2)BinaryOperator<T>
  1. 两个入参,通常被用在比较大小(max、min),合并(reduce)等场景。
  2. 返回值为基础类型的扩展类:IntBinaryOperator、LongBinaryOperator、DoubleBinaryOperator。

5. 条件判断型

(1)Predicate<T>
  1. 相当于返回值为 boolean 的 Function<T, boolean>。
  2. 具备常用的 and、or、negate(取反)方法。
  3. 扩展类:IntPredicate、LongPredicate、DoublePredicate。
(2)BiPredicate<T, U>
  1. 相当于返回值为 boolean 的 BiFunction<T, U, boolean>。

6. 总结

自此,JAVA8 的 java.util.function 包里全部类都简要介绍完毕啦,大家学废了吗?