Sobes.tech
Junior — Middle

Can you explain how the Collections.sort() method works in Java and what are its advantages?

sobes.tech AI

Answer from AI

The Collections.sort() method in Java is used to sort elements of a list that implements the List interface. By default, it sorts elements in their natural order if they implement Comparable. You can also pass a Comparator to define a custom order.

The underlying algorithm of Collections.sort() is TimSort — a hybrid of merge sort and insertion sort, optimized for real-world data. It is efficient in time and space.

Advantages:

  • Easy to use — just call the method with the list.
  • Flexible — you can specify your order via a comparator.
  • High performance due to TimSort.

Example:

List<String> names = Arrays.asList("Anna", "John", "Mike");
Collections.sort(names); // sorts alphabetically

// Sort by string length
Collections.sort(names, Comparator.comparingInt(String::length));