问题
I have this list:
List<Country> countryList = new ArrayList<Country>();
And I want to sort the countries by their name, by using the method getCountry()
.
How can achieve this?
UPDATE:
public class Country implements Comparable
@Override
public int compareTo(Object another) {
// TODO Auto-generated method stub
return 0;
}
Can you tell how to compare them to get it sorted by Strings? Argentina, Austria, Brazil, etc.
回答1:
There are two ways:
Have
Country
implement the java.util.Comparable interface to define a natural ordering on yourCountry
objects, i.e. make the objects themselves "know" their ordering. You can then use Collections.sort(List) or just switch from yourList
to aSortedSet
implementation likeTreeSet
(if you don't need duplicates, aSet
drops duplicates)Write a java.util.Comparator to define an imposed ordering and call Collections.sort(List, Comparator) or (losing duplicates again) go for a
new TreeSet(Comparator)
.
Implementing one of these two is enough to solve your problem -- both Comparable
and Comparator
can be combined, though: using a Comparator
will override any natural ordering defined by Comparable
.
回答2:
You can call Collections.sort() providing a Comparator which compares the getCountry().
回答3:
Use the built in sort method and make sure you implement comparable on Country
来源:https://stackoverflow.com/questions/7776822/sort-listt-of-objects-by-a-particular-rule