Java record-61-Comparator
Public interface Comparator <T> is a comparison function that forcibly sorts the collection objects. Comparator can be passed to the sort method (such as Collections. sort or Arrays. sort) to allow precise control over the sorting order. You can also use Comparator to control the order of certain data structures (such as ordered set or ordered ing), or provide sorting for object collections without natural order. Natural sorting: for example, the numbers 1, 2, 3, 4, and 5; the letters a, B, c, and d are sorted by default for the original type or String type, you can directly use the collection class for sorting. However, if the custom object is added to the Collection class to be sorted, the collection class does not know its sorting rules and needs to tell the collection class the sorting rules for the new object. We need to implement our own sorting class, that is, implement Comparator. To implement Comparator, you must implement the compare method: int compare (Object o1, Object o2). This method returns an integer of the basic type, and a negative number indicates that o1 is less than o2, if the return value is 0, the values of o1 and o2 are equal. If the return value is positive, the values of o1 are greater than o2.
public class TreeSetTest { public static void main(String[] args){ TreeSet tree = new TreeSet(new MyComparator()); tree.add(new Person(24)); tree.add(new Person(33)); tree.add(new Person(21)); tree.add(new Person(20)); System.out.println(tree); //[20, 21, 24, 33] }}class Person{ int age; String name; public Person(int age){ this.age = age; } public String toString(){ return String.valueOf(this.age); }}class MyComparator implements Comparator{ public int compare(Object o1, Object o2) { Person p1 = (Person)o1; Person p2 = (Person)o2; return p1.age - p2.age; }}
TreeSet storage is ordered. We need to customize MyComparator for the sorting rules of our custom Person objects and tell the TreeSet constructor so that the TreeSet can store our custom Person objects, sort the stored objects according to the defined sorting rules. (Sort by the age attribute size of Person ).