I have this list:
List countryList = new ArrayList();
And I want to sort the countries by their name, by usin
There are two ways:
Have Country
implement the java.util.Comparable interface to define a natural ordering on your Country
objects, i.e. make the objects themselves "know" their ordering. You can then use Collections.sort(List) or just switch from your List
to a SortedSet
implementation like TreeSet
(if you don't need duplicates, a Set
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
.
Use the built in sort method and make sure you implement comparable on Country
You can call Collections.sort() providing a Comparator which compares the getCountry().