Collections: Collections.max and min take an optional Comparator

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.

Code
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)));
Output
Max by natural order: kiwi
Max by length: banana
Min by length: fig
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