1. The Collections tool class provides a static method sort method. The input parameter is a List collection. Compared with Comparator, the given List collection is sorted. The above example code creates an anonymous inner class to participate in. This kind of similar operation can be seen everywhere in our daily work.
List<String> names = Arrays.asList("peter", "anna", "mike", "xenia"); Collections.sort(names, new Comparator<String>() { @Override public int compare(String a, String b) { return b.compareTo(a); } });
2. Use Lambda expressions
For code blocks that only contain one line of methods, we can omit the curly brackets and directly return the key code, which can be simpler.
Collections.sort(names, (String a, String b) -> b.compareTo(a));
Collections in Java are mainly divided into four categories:
1. List: ordered, repeatable;
2. Queue: ordered and repeatable;
3. Set: non-repeatable;
4. Map: unordered, with unique keys and non-unique values.
The above is the detailed content of What are the methods for sorting collections in java. For more information, please follow other related articles on the PHP Chinese website!