I have a TreeTable
and would like to perform the sort by number and alphabetically when clicking on header.
Example:
- On a first click, I have to check that the column content is sorted by number
- If I click on another column that contains
String
data, I have to check that column content is sorted alphabetically.
Are there known functions that could I use?
I've used Collections for sorting number , but how d开发者_Python百科o I can make the sort alphabetically ? Collections.sor(myList) is OK for sorting by number but I would sort data alphabetically.
thanks
This can easily be done via Collections.sort(...)
. Create a copy of your list, sort it and check if they are equal.
Example:
List <String> copy = new ArrayList <String>(original);
Collections.sort(copy);
assertEquals(copy, original);
This can be done, if the elements in the list are comparable (i.e. are of type T implements Comparable <T>
). Strings are comparable, and their default comparator sorts them alphabetically (though upper-case are always comes before lower-case)
You may also provide a Comparator
for a more flexible sorting.
Here is a more complicated example.
List <String> unholyBible = new ArrayList <String>();
unholyBible.add("armageddon");
unholyBible.add("abyss");
unholyBible.add("Abaddon");
unholyBible.add("Antichrist");
Collections.sort(unholyBible);
System.out.println(unholyBible);
This will print us [Abaddon, Antichrist, abyss, armageddon]
. This is because default comparation is case-sensitive. Lets fix it:
List <String> unholyBible = new ArrayList <String>();
unholyBible.add("armageddon");
unholyBible.add("abyss");
unholyBible.add("Abaddon");
unholyBible.add("Antichrist");
Collections.sort(unholyBible, new Comparator <String>() {
public int compare(String o1, String o2){
return o1.compareToIgnoreCase(o2);
}
});
System.out.println(unholyBible);
This one prints [Abaddon, abyss, Antichrist, armageddon]
.
Now you may worship Satan in strict alphabetical order.
See also
- Comparator API
- Collections.sort(List, Comparator)
精彩评论