How do you sort elements in a collection in Java?
In Java, you can use the sort() method from the Collections class to sort elements in a collection. The sort() method has two overloaded forms, one for sorting elements in a List collection, and another for sorting elements in a List collection based on a specified comparator.
Sort the elements in a List collection.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SortExample {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(5);
numbers.add(3);
numbers.add(1);
numbers.add(4);
numbers.add(2);
Collections.sort(numbers);
System.out.println(numbers);
}
}
Output results:
[1, 2, 3, 4, 5]
Sort the elements in a List collection using a specified comparator.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class SortExample {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("John");
names.add("Alice");
names.add("Bob");
names.add("David");
names.add("Catherine");
// 根据字符串长度进行排序
Comparator<String> lengthComparator = Comparator.comparingInt(String::length);
Collections.sort(names, lengthComparator);
System.out.println(names);
}
}
Output result:
[Bob, John, Alice, David, Catherine]
The above code demonstrates how to sort integers and strings, but Java’s Collections.sort() method can only sort classes that implement the Comparable interface. If you want to sort custom classes, you need to make the class implement the Comparable interface and define the comparison rules in the compareTo() method. Alternatively, you can use a Comparator to sort elements in a collection without modifying the class definition of the elements.