Sort List<T> of objects by a particular rule?

[亡魂溺海] 提交于 2019-12-29 09:25:07

问题


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:

  1. 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)

  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!