假设我有以下对象类:
optparse.parse
我有一个包含许多对象的对象列表:
rest = optparse.parse!
我如何根据public class Country {
private int ID;
private String name;
private Double distance;
}
对列表进行排序,例如先放置距离较小的对象?有没有准备好的功能呢?
或者我想在另一个列表中存储3个最小距离的国家/地区。
答案 0 :(得分: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());
}
});