Collections: List.sort with a comparator beats Collections.sort

List.sort is the instance method added in Java 8 and is the modern form. Passing null uses natural ordering.

Code
var words = new ArrayList<>(List.of("kafka", "java", "sql", "hibernate"));

words.sort(Comparator.comparingInt(String::length).thenComparing(Comparator.naturalOrder()));
System.out.println("by length then alphabetical: " + words);

words.sort(null);
System.out.println("sort(null) = natural order : " + words);

words.sort(Comparator.reverseOrder());
System.out.println("reverse order              : " + words);
Output
by length then alphabetical: [sql, java, kafka, hibernate]
sort(null) = natural order : [hibernate, java, kafka, sql]
reverse order              : [sql, kafka, java, hibernate]
Advertisement

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-07-30