Sort List of objects by a particular rule?

前端 未结 3 1535
悲&欢浪女
悲&欢浪女 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.

    0 讨论(0)
  • 2020-12-22 04:07

    Use the built in sort method and make sure you implement comparable on Country

    0 讨论(0)
  • 2020-12-22 04:18

    You can call Collections.sort() providing a Comparator which compares the getCountry().

    0 讨论(0)
提交回复
热议问题