Lambda: BinaryOperator.minBy and maxBy turn a Comparator into a reducer

BinaryOperator.minBy(comparator) builds a two-argument function that returns the smaller argument, so a Comparator can drive reduce or Map.merge directly without writing a ternary.

Code
record Bid(String bidder, int amount) {}
BinaryOperator<Bid> highest = BinaryOperator.maxBy(Comparator.comparingInt(Bid::amount));
BinaryOperator<Bid> lowest = BinaryOperator.minBy(Comparator.comparingInt(Bid::amount));
var bids = List.of(new Bid("ana", 120), new Bid("raj", 180), new Bid("li", 95));
System.out.println("Highest: " + bids.stream().reduce(highest).orElseThrow());
System.out.println("Lowest:  " + bids.stream().reduce(lowest).orElseThrow());
Map<String, Integer> best = new TreeMap<>();
best.merge("lot-7", 100, BinaryOperator.maxBy(Comparator.naturalOrder()));
best.merge("lot-7", 140, BinaryOperator.maxBy(Comparator.naturalOrder()));
best.merge("lot-7", 110, BinaryOperator.maxBy(Comparator.naturalOrder()));
System.out.println("Best per lot: " + best);
Output
Highest: Bid[bidder=raj, amount=180]
Lowest:  Bid[bidder=li, amount=95]
Best per lot: {lot-7=140}
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms