排序android中的对象列表

MSM*_*SMC 2 java sorting android list

假设我有以下对象类:

public class Country {
    private int ID;
    private String name;
    private Double distance;
}
Run Code Online (Sandbox Code Playgroud)

我有一个包含许多对象的对象列表:

List<Country> myList;
Run Code Online (Sandbox Code Playgroud)

我如何根据Double distance例如先放置距离较小的物体对列表进行排序?有没有准备好的功能呢?

或者我想在另一个列表中存储3个最小距离的国家/地区.

ΦXo*_*a ツ 8

使用Collection.sort并传递您自己的实现Comparator

例:

List<Country> items = new ArrayList<Country>();

.....
Collections.sort(items, new Comparator<Country>() {

    @Override
    public int compare(Country o1, Country o2) {
        return Double.compare(o1.getDistance(), o2.getDistance());
    }

});
Run Code Online (Sandbox Code Playgroud)