Collections.max and min default to natural ordering but accept a Comparator, letting the same list be ranked by a different key without sorting it first.
List<String> words = List.of("kiwi", "fig", "banana", "apple");
System.out.println("Max by natural order: " + Collections.max(words));
System.out.println("Max by length: " + Collections.max(words, Comparator.comparingInt(String::length)));
System.out.println("Min by length: " + Collections.min(words, Comparator.comparingInt(String::length)));
Max by natural order: kiwi
Max by length: banana
Min by length: fig
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