BiFunction, UnaryOperator and BinaryOperator
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)When a lambda needs two inputs, Java has Bi versions of the core interfaces: BiFunction, BiPredicate and BiConsumer. When the input and the result have the same type, the operators UnaryOperator and BinaryOperator say so in their name.
Two inputs: BiFunction, BiPredicate and BiConsumer
BiFunction<T, U, R> is a functional interface with two inputs and one result: R apply(T t, U u). The Bi interfaces are the two-input versions of Function, Predicate and Consumer.
Many rules need two values: price and quantity give a bill total, a user ID and a PIN give a login result. Without two-input interfaces you would pack both values into one object first.
Example 1 · BiFunction, BiPredicate and BiConsumer
import java.util.Map;import java.util.TreeMap;import java.util.function.BiConsumer;import java.util.function.BiFunction;import java.util.function.BiPredicate;
public class TwoInputsDemo { public static void main(String[] args) { BiFunction<Integer, Integer, Integer> lineTotal = (price, qty) -> price * qty; System.out.println("3 notebooks at Rs. 15: " + lineTotal.apply(15, 3));
BiPredicate<String, String> canLogin = (user, pin) -> user.equals("kavya") && pin.equals("4821"); System.out.println("kavya / 4821: " + canLogin.test("kavya", "4821")); System.out.println("kavya / 1111: " + canLogin.test("kavya", "1111"));
Map<String, Integer> marks = new TreeMap<>(); marks.put("Rohan", 82); marks.put("Divya", 58); marks.put("Arjun", 91);
BiConsumer<String, Integer> printRow = (name, m) -> System.out.println(name + " scored " + m); marks.forEach(printRow); }}3 notebooks at Rs. 15: 45 kavya / 4821: true kavya / 1111: false Arjun scored 91 Divya scored 58 Rohan scored 82
What this code does
- Each
Biinterface keeps its family's method name,apply,testoraccept, with two parameters in brackets:(price, qty) -> .... Map.forEachtakes aBiConsumer<K, V>and calls it once per entry, so you get the key and the value directly. ATreeMapgives them in name order.
There is no BiSupplier, because a supplier takes no input at all. The most common place you meet one is Map.forEach. It hands every key and value pair to a BiConsumer<K, V>, so marks.forEach((name, m) -> ...) needs no Map.Entry and no getKey().
The three Bi interfaces, with inputs of types T and U:
BiFunction<T, U, R>:R apply(T t, U u). Example:(price, qty) -> price * qty.BiPredicate<T, U>:boolean test(T t, U u). Example:(user, pin) -> ...for a login check.BiConsumer<T, U>:void accept(T t, U u). Example:(name, marks) -> System.out.println(...).
UnaryOperator<T>: same type in and out
An operator is a function whose result has the same type as its input. UnaryOperator<T> is a Function<T, T> with a shorter, clearer name: "unary" means it takes one value. Trimming a name, adding grace marks and applying a discount are all unary operators.
Example 2 · UnaryOperator with List.replaceAll
import java.util.ArrayList;import java.util.List;import java.util.function.UnaryOperator;
public class ReplaceAllDemo { public static void main(String[] args) { List<String> names = new ArrayList<>(List.of(" rohan", "KAVYA ", " divya ")); UnaryOperator<String> clean = s -> { String t = s.trim().toLowerCase(); return Character.toUpperCase(t.charAt(0)) + t.substring(1); }; names.replaceAll(clean); System.out.println(names);
List<Integer> marks = new ArrayList<>(List.of(33, 97, 64)); UnaryOperator<Integer> graceMarks = m -> Math.min(100, m + 5); marks.replaceAll(graceMarks); System.out.println(marks); }}[Rohan, Kavya, Divya] [38, 100, 69]
What this code does
replaceAllcalls the operator on every item and writes the result back in the same position, so the list changes in place.UnaryOperator<String>says "String in, String out" with one type argument.Math.min(100, ...)keeps grace marks from going above 100, so 97 becomes 100, not 102.
Example 3 · Mistake: a Function where replaceAll needs an operator
import java.util.ArrayList;import java.util.List;import java.util.function.Function;
public class WrongTypeDemo { public static void main(String[] args) { List<String> cities = new ArrayList<>(List.of("pune", "goa")); Function<String, String> upper = s -> s.toUpperCase(); cities.replaceAll(upper); System.out.println(cities); }}WrongTypeDemo.java:9: error: incompatible types: Function<String,String> cannot be converted to UnaryOperator<String>
cities.replaceAll(upper);
^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 errorWhat this code does
replaceAllwants aUnaryOperator<String>.UnaryOperatorextendsFunction, not the other way round, so aFunctionvariable is not accepted even though its types match.- Fix: declare
UnaryOperator<String> upper = s -> s.toUpperCase();, or pass the lambda straight in:cities.replaceAll(s -> s.toUpperCase());, where Java makes it aUnaryOperatorfor you.
List.replaceAll takes a UnaryOperator<E>. It calls the operator on every item and puts the result back in the same place. The result goes into the same list, so it must have the same type; that is why the parameter is an operator and not a general Function. UnaryOperator<T> extends Function<T, T>. So a UnaryOperator can be passed wherever a Function<T, T> is expected, but not the other way round: a variable declared as Function<String, String> cannot be passed to replaceAll.
BinaryOperator<T>: combine two values into one
BinaryOperator<T> takes two values of type T and returns one T: (a, b) -> a + b. It extends BiFunction<T, T, T>. Adding, taking the larger, and joining two Strings are binary operators.
- If the key is missing,
mergesimply putsvaluein the map. - If the key is present, it calls
remapping.apply(oldValue, value)and stores the result. - For word counts, call
counts.merge(word, 1, (a, b) -> a + b)for each word: the first time stores 1, later times add 1. - If the remapping returns
null,mergeremoves the key, a rarely used way to delete.
Example 4 · BinaryOperator with Map.merge: word counts
import java.util.Map;import java.util.TreeMap;import java.util.function.BinaryOperator;
public class WordCountDemo { public static void main(String[] args) { String feedback = "good teacher good notes clear notes good"; String[] words = feedback.split(" ");
// old way: containsKey, get, put Map<String, Integer> oldCounts = new TreeMap<>(); for (String w : words) { if (oldCounts.containsKey(w)) { oldCounts.put(w, oldCounts.get(w) + 1); } else { oldCounts.put(w, 1); } } System.out.println("Old way: " + oldCounts);
// new way: merge with a BinaryOperator BinaryOperator<Integer> add = (a, b) -> a + b; Map<String, Integer> counts = new TreeMap<>(); for (String w : words) { counts.merge(w, 1, add); } System.out.println("merge: " + counts); }}Old way: {clear=1, good=3, notes=2, teacher=1}
merge: {clear=1, good=3, notes=2, teacher=1}What this code does
- For "good", the first
mergefinds no key and stores 1. The next two find 1 and then 2, and calladd.apply(old, 1), giving 3. - Both ways give the same map.
mergeneeds noifand touches the map once per word;addis aBinaryOperator<Integer>because it combines twoIntegers into one.
Its best-known use is Map.merge(key, value, remapping), the cleanest way to count. merge takes a BiFunction with the operator shape (old, new) -> result, so a BinaryOperator fits it:
containsKey, get and put, and an if. merge does the same in one line.minBy and maxBy: an operator from a Comparator
BinaryOperator.minBy(comparator) and BinaryOperator.maxBy(comparator) are static methods. They turn a Comparator into an operator that returns the smaller or the larger of its two inputs. For a tie, both return the first argument.
Example 5 · minBy and maxBy: best attempt and cheapest offer
import java.util.Comparator;import java.util.Map;import java.util.TreeMap;import java.util.function.BinaryOperator;
public class MinMaxByDemo { public static void main(String[] args) { String[] names = {"Rohan", "Kavya", "Rohan", "Kavya", "Rohan"}; int[] scores = {62, 88, 79, 71, 74};
Map<String, Integer> best = new TreeMap<>(); BinaryOperator<Integer> higher = BinaryOperator.maxBy(Comparator.naturalOrder()); for (int i = 0; i < names.length; i++) { best.merge(names[i], scores[i], higher); } System.out.println("Best attempts: " + best);
BinaryOperator<String> shorter = BinaryOperator.minBy(Comparator.comparingInt(s -> s.length())); System.out.println(shorter.apply("Chennai", "Goa")); System.out.println(shorter.apply("Pune", "Agra")); }}Best attempts: {Kavya=88, Rohan=79}
Goa
PuneWhat this code does
maxBy(Comparator.naturalOrder())builds an operator that returns the largerInteger. Withmerge, each student keeps only their highest score.minByworks with any comparator, here by length. "Pune" and "Agra" tie at 4 letters, andminByreturns the first argument for a tie.
They are handy with merge. To keep each student's best attempt, call best.merge(name, score, BinaryOperator.maxBy(Comparator.naturalOrder())). Any comparator works, so minBy(Comparator.comparingInt(...)) can keep the cheapest offer for each product.
Choose the most specific interface
Several interfaces can hold the same lambda. (a, b) -> a + b on Integer fits BiFunction<Integer, Integer, Integer> and BinaryOperator<Integer>. Both compile, but the shorter, more specific name tells the reader more: "this combines two values of one type".
BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b; // compilesBinaryOperator<Integer> total = (a, b) -> a + b; // same lambda, clearer nameBiFunction<Integer, Integer, Double> average = (a, b) -> (a + b) / 2.0; // result type differsList<String> names = new ArrayList<>(List.of("asha", "ravi"));names.replaceAll(s -> s.toUpperCase()); // needs a UnaryOperator<String>The specific type is also what some methods require. replaceAll accepts only a UnaryOperator. In the other direction, when the result type differs, an operator cannot be used: an average of two Integer marks is a Double, so it must be BiFunction<Integer, Integer, Double>.
- One input, any result:
Function<T, R>. Same type in and out:UnaryOperator<T>. - Two inputs, any result:
BiFunction<T, U, R>. Two of one type giving that type:BinaryOperator<T>. - Two inputs, yes or no:
BiPredicate<T, U>. Two inputs, no result:BiConsumer<T, U>.
Next step
Check your understanding
12 quick questions