After using collections to collect objects, if the relative objects are sorted, we can use the sort () method in Java.util.Collections, because an index is required to sort, so the collections sort () method is subject to the list action object. Use the sort () method to sort objects only according to the sort method it provides, and if you want to define collations yourself, you can manipulate the CompareTo () method in Java.util.Comparable. or the Compara () method in the Java.util.Comparator interface.
difference: The CompareTo () method of the comparable must override the method within the object of the comparison, such as the string class itself has an operation comparable, and the following sort
List words = arrays.aslist ("B", "X", "A");
Collections.sort (words);
It will get the result: A B X
If you need to sort reverse order at this point, you need to override the CompareTo () method inside the string class, so using CompareTo () is inconvenient in some cases
The Compara () method in the comparator interface does not have this requirement, it can override the Compara () method in another class, and finally call the class
list<map.entry<string, integer>> list = new arraylist<> (Map.entryset ());
Collections.sort (list, new Valuesort ());
for (int i = 0; i < list.size (); i++)
System.out.print (List.get (i) getkey ());
Class Valuesort implements Comparator<map.entry<string, integer>> {
@Override public
int Compare ( Entry<string, integer> O1, entry<string, integer> O2) {
if ((O1.getvalue ()-O2.getvalue ()) > 0)
R eturn-1;
else if (O1.getvalue ()-o2.getvalue () = 0)
&& (O1.getkey (). CharAt (0)-O2.getkey (). CharAt (0) > 0)
return-1;
return 1;
}
}
Rewrite the Compare () method in class Valuesort, and then use Collections.sort (list, new Valuesort ()) to call the class and sort the list