Java Collections.sort: How to Sort Lists
The Collections.sort method is used to sort the elements in a collection. It takes a parameter of type List and sorts the elements in the List. The way in which the elements are sorted depends on their natural order, or can be determined by the provided Comparator. The sorted result will replace the original List.
For example, you can use the Collections.sort method to sort a List.
List<Integer> list = new ArrayList<>();
list.add(3);
list.add(1);
list.add(2);
Collections.sort(list);
System.out.println(list); // 输出:[1, 2, 3]
You can also use the Collections.sort method to sort a List by using a customized Comparator.
List<String> list = new ArrayList<>();
list.add("banana");
list.add("apple");
list.add("cherry");
Collections.sort(list, (s1, s2) -> s1.compareTo(s2));
System.out.println(list); // 输出:[apple, banana, cherry]