Skip to content

Towards Declarative Programming

Chen YiJia edited this page Mar 20, 2021 · 2 revisions

The Weird World of Functional Interfaces

Predicate: takes an argument and returns a boolean.

Function: argument and return types differ.

Supplier: takes no argument and returns a value.

Consumer: takes an argument and returns nothing.

Interface Function Signature Example
Predicate<T> boolean test(T t) Collection::isEmpty
Function<T,R> R apply(T t) Arrays::asList
Supplier<T> T get() Math::random
Consumer<T> void accept(T t) System.out::println

Primitive Variations

There are three variants of each of the above interfaces to operate on the primitive types int, long and double. Their names are derived from the basic interfaces by prefixing then with a primitive type.

Examples: IntPredicate, LongFunction<int[]>, DoubleSupplier.

Function Variations

For use when the result type is primitive.

  • If both the sources and result types are primitive, prefix Function with SrcToResult, for example LongToIntFunction.
  • If the source is a primitive and the result is an object reference, prefix Function with <Src>ToObj, for example DoubleToObjFunction.

2-Argument Variations

BiPredicate<T,U>, BiFunction<T,U,R>, and BiConsumer<T,U>.

  • There are also BiFunction variants returning the three relevant primitive types: ToIntBiFunction<T,U>, ToLongBiFunction<T,U> and ToDoubleBiFunction<T,U>.

  • There are two-argument variants of Consumer that take one object reference and one primitive type: ObjDoubleConsumer<T>, ObjIntConsumer<T> and ObjLongConsumer<T>.

Others

BooleanSupplier, a variant of Supplier that returns boolean values.