Sobes.tech
Junior — Middle

How can you sort a list of elements in your program?

sobes.tech AI

Answer from AI

In Java, to sort a list of elements, the Collections.sort() method or the sort() method of the List interface, available since Java 8, are commonly used.

If the list elements implement the Comparable interface, you can simply call:

List<String> list = Arrays.asList("banana", "apple", "orange");
Collections.sort(list);

To sort by a custom criterion, use a Comparator:

List<Person> people = ...;
people.sort(Comparator.comparing(Person::getAge));

You can also use lambda expressions to define the order:

people.sort((p1, p2) -> p1.getName().compareTo(p2.getName()));

Thus, sorting in Java is flexible and can be performed either by natural order or by any specified criterion.