Sort List of objects by a particular rule?

前端 未结 3 1627
悲&欢浪女
悲&欢浪女 2020-12-22 04:00

I have this list:

List countryList = new ArrayList();

And I want to sort the countries by their name, by usin

3条回答
  •  一整个雨季
    2020-12-22 04:07

    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.

提交回复
热议问题