min and max with a Comparator
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)min and max are terminal operations that return the smallest or largest element of a stream. You decide what "smallest" means by passing a Comparator, so the same call finds the topper, the cheapest phone or the longest name.
min and max need a Comparator
Without streams, finding the topper takes a loop: keep a best variable, compare every student with it, and replace it when a better one comes. You must also decide what best starts as when the list is empty.
Example 1 · min and max on numbers
import java.util.Comparator;import java.util.List;import java.util.Optional;
public class MinMaxNumbersDemo { public static void main(String[] args) { List<Integer> marks = List.of(72, 38, 91, 64, 55);
// old way: a loop with a running best value int best = marks.get(0); for (int m : marks) { if (m > best) { best = m; } } System.out.println("Loop max: " + best);
Optional<Integer> highest = marks.stream().max(Comparator.naturalOrder()); Optional<Integer> lowest = marks.stream().min(Integer::compare);
System.out.println("Stream max: " + highest); System.out.println("Stream min: " + lowest); System.out.println("Highest value: " + highest.get()); System.out.println("Range: " + (highest.get() - lowest.get())); }}Loop max: 91 Stream max: Optional[91] Stream min: Optional[38] Highest value: 91 Range: 53
What this code does
maxandminon aStream<Integer>need a comparator.Comparator.naturalOrder()and the method referenceInteger::compareboth compare numbers from small to large.- The result is an
Optional, so printing it showsOptional[91].get()takes the value out; it is safe here because the list is not empty.
Example 2 · Trap: Stream has no max() without a Comparator
import java.util.List;
public class MaxTrapDemo { public static void main(String[] args) { List<Integer> marks = List.of(72, 38, 91, 64); System.out.println(marks.stream().max()); }}MaxTrapDemo.java:6: error: method max in interface Stream<T> cannot be applied to given types;
System.out.println(marks.stream().max());
^
required: Comparator<? super Integer>
found: no arguments
reason: actual and formal argument lists differ in length
where T is a type-variable:
T extends Object declared in interface Stream
1 errorWhat this code does
marks.stream()is aStream<Integer>, andStream.maxalways needs a comparator. The error says it plainly: requiredComparator, found no arguments.- Fix:
marks.stream().max(Comparator.naturalOrder())ormax(Integer::compare). OnlyIntStream, frommapToInt, has amax()with no argument.
A stream does the same with one call: students.stream().max(byMarks). Stream<T> has no plain max(), because a stream of Student objects has no single obvious order. You pass a Comparator<T>, the same object you used for sorting in the Collections section. For numbers and Strings, the ready-made Comparator.naturalOrder() works, and so does a method reference such as Integer::compare. min(cmp) returns the element that comes first in the comparator's order; max(cmp) returns the one that comes last.
Comparator.comparing picks the field
Comparator.comparingInt(Student::marks) builds a comparator from the sort key, the value being compared. With it, max finds the topper and min finds the lowest scorer. Comparator.comparingDouble(Product::price) with min finds the cheapest product.
Example 3 · The topper and the cheapest product
import java.util.Comparator;import java.util.List;
record Student(String name, String branch, int marks) {}
record Product(String name, double price) {}
public class TopperDemo { public static void main(String[] args) { List<Student> students = List.of( new Student("Aarav", "CSE", 78), new Student("Priya", "ECE", 92), new Student("Rohan", "CSE", 85), new Student("Kavya", "MECH", 69));
Student topper = students.stream() .max(Comparator.comparingInt(Student::marks)) .get(); System.out.println("Topper: " + topper.name() + " " + topper.marks());
Student cseTopper = students.stream() .filter(s -> s.branch().equals("CSE")) .max(Comparator.comparingInt(Student::marks)) .get(); System.out.println("CSE topper: " + cseTopper.name());
List<Product> cart = List.of( new Product("Earphones", 799.0), new Product("Charger", 549.5), new Product("Cover", 299.0)); Product cheapest = cart.stream() .min(Comparator.comparingDouble(Product::price)) .get(); System.out.println("Cheapest: " + cheapest);
String longest = students.stream() .map(Student::name) .max(Comparator.comparingInt(String::length)) .get(); System.out.println("Longest name: " + longest); }}Topper: Priya 92 CSE topper: Rohan Cheapest: Product[name=Cover, price=299.0] Longest name: Aarav
What this code does
Comparator.comparingInt(Student::marks)says "compare by marks".maxwith it returns the topper;filterbefore it limits the search to one branch.minwith a price comparator returns the cheapest product.- The last pipeline maps to names and compares by length. All four names have 5 letters, so the first one, Aarav, wins the tie.
Any comparator works, including reversed() and thenComparing. min(cmp.reversed()) gives the same element as max(cmp), but max(cmp) is clearer to read. A min or max call reads the stream once, so it takes O(n) time. Sorting the whole list and taking the first element takes O(n log n) and changes or copies the list, just to read one item.
Why the result is an Optional
An empty stream has no smallest element. Older code returned null for "nothing found", and a forgotten null check crashed later with a NullPointerException.
Example 4 · Reading an Optional result safely
import java.util.Comparator;import java.util.List;import java.util.Optional;
public class EmptyResultDemo { public static void main(String[] args) { List<Integer> todaysOrders = List.of(450, 1200, 300); List<Integer> noOrders = List.of();
Optional<Integer> biggest = todaysOrders.stream().max(Comparator.naturalOrder()); Optional<Integer> none = noOrders.stream().max(Comparator.naturalOrder());
System.out.println(biggest); System.out.println(none); System.out.println("Has a value? " + none.isPresent());
// orElse: the value, or a default when empty System.out.println("Biggest order: " + biggest.orElse(0)); System.out.println("Biggest order: " + none.orElse(0));
// ifPresent: run only when there is a value biggest.ifPresent(b -> System.out.println("Send thank-you coupon for Rs. " + b)); none.ifPresent(b -> System.out.println("This line never prints"));
Optional<Integer> bigAfterFilter = todaysOrders.stream() .filter(a -> a > 5000) .max(Comparator.naturalOrder()); System.out.println("Over 5000: " + bigAfterFilter); }}Optional[1200] Optional.empty Has a value? false Biggest order: 1200 Biggest order: 0 Send thank-you coupon for Rs. 1200 Over 5000: Optional.empty
What this code does
- An empty list, or a
filterthat drops everything, givesOptional.empty. The code never sees anull. orElse(0)gives a default, andifPresentruns its lambda only when a value is inside. Callingnone.get()instead would throwNoSuchElementException: No value present.
So min and max return an Optional<T>: a small box that holds either one value or nothing. Printing it shows Optional[91] or Optional.empty. The type itself reminds you that the answer may be missing. Read it safely with orElse(other), which gives the value or a default, or with ifPresent(action), which runs only when there is a value. isPresent() tells you if a value is inside. get() returns the value but throws NoSuchElementException ("No value present") on an empty box, so use it only right after a check. The Optional Values module covers the rest of this class.
IntStream, max() takes no comparator and returns an OptionalInt. The Primitive and Parallel Streams module covers it.Ties: which element wins
Two students may share the top marks. On a sequential stream, today's JDK returns the first of the tied elements in encounter order, for both min and max. The documentation does not promise this, so do not build a report on it.
Example 5 · Ties: the first one wins, unless you break the tie
import java.util.Comparator;import java.util.List;
record Student(String name, int marks) {}
public class TieDemo { public static void main(String[] args) { List<Student> students = List.of( new Student("Rohan", 91), new Student("Aarav", 80), new Student("Kavya", 91), new Student("Divya", 80));
Comparator<Student> byMarks = Comparator.comparingInt(Student::marks); System.out.println("max: " + students.stream().max(byMarks).get().name()); System.out.println("min: " + students.stream().min(byMarks).get().name());
// a clear tie-breaker: same marks, then the name earlier in A to Z wins Comparator<Student> byMarksThenName = byMarks.thenComparing(Student::name, Comparator.reverseOrder()); System.out.println("max with tie-breaker: " + students.stream().max(byMarksThenName).get().name());
// every topper, not just one int top = students.stream().max(byMarks).get().marks(); students.stream() .filter(s -> s.marks() == top) .forEach(s -> System.out.println("Topper: " + s.name())); }}max: Rohan min: Aarav max with tie-breaker: Kavya Topper: Rohan Topper: Kavya
What this code does
- Rohan and Kavya tie on 91; Aarav and Divya tie on 80. Both
maxandminreturned the first tied student in the list. That is how the JDK works today, but it is not a written promise. thenComparing(Student::name, Comparator.reverseOrder())makes the name decide ties: formax, the name that comes first in A to Z must count as "larger", so the name order is reversed. To list every topper, find the top marks, thenfilter.
If ties matter, say how to break them. Add a second key with thenComparing, for example marks and then name. If you need every topper, find the top marks first, then filter all students with those marks.
Next step
Check your understanding
11 quick questions