BiFunction & Supplier (Java 8)
BiFunction<T, U, R>
- What: A functional interface that takes two inputs and returns one result.
-
Signature:
R apply(T t, U u)
-
Extras:
default <V> BiFunction<T, U, V> andThen(Function<? super R, ? extends V> after)
- When to use: combine two values, compute/merge/map from two inputs.
-
Related:
-
BinaryOperator<T>
=BiFunction<T,T,T>
(same type for both inputs & result) - Primitive specials:
ToIntBiFunction<T,U>
,ToLongBiFunction<T,U>
,ToDoubleBiFunction<T,U>
-
Examples
// combine two inputs
BiFunction<Integer, Double, Double> total = (qty, price) -> qty * price;
// chain result
BiFunction<Integer, Double, String> label =
total.andThen(t -> "Total: " + t);
// Map.merge uses a BiFunction
Map<String,Integer> counts = new HashMap<>();
counts.merge("apple", 1, Integer::sum); // (oldVal, newVal) -> oldVal + newVal
Supplier
- What: A functional interface that supplies a value; takes no input, returns T.
-
Signature:
T get()
- When to use: lazy creation, factories, fallbacks, stream generators.
-
Related: Primitive specials:
IntSupplier
,LongSupplier
,DoubleSupplier
,BooleanSupplier
Examples
// constructor/factory
Supplier<List<String>> listFactory = ArrayList::new;
List<String> list = listFactory.get();
// lazy fallback (only runs if null)
String value = Optional.ofNullable(System.getenv("CFG"))
.orElseGet(() -> loadFromFile());
// infinite stream source
Stream.generate(UUID::randomUUID)
.limit(3)
.forEach(System.out::println);
Constructor method references
class User { User(String name, int age) { /*...*/ } }
BiFunction<String,Integer,User> userFactory = User::new; // two args â BiFunction
Supplier<User> emptyUserFactory = () -> new User("guest", 0); // no args â Supplier
Rule of thumb
- Need to combine two inputs into one result? â BiFunction
- Need to defer or centralize creation of a value with no inputs? â Supplier