Suppose I have the following object class:
public class Country {
private int ID;
private String name;
private Double distance;
}
and I have a list of this object which contain many objects:
List<Country> myList;
how i can sort the list based on the Double distance
e.g to put objects with less distance first? Is there a ready function to do this?
Or i want to store 3 countries of minimum distances in another list.
Pshemo
125k25 gold badges194 silver badges280 bronze badges
asked May 6, 2016 at 16:09
1 Answer 1
Use Collection.sort
and pass your own implementation of Comparator
Example:
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());
}
});
answered May 6, 2016 at 16:14
4 Comments
Pshemo
Comparator doesn't need to be anonymous. Maybe it is better to reword it as "your own" or something similar to avoid possible misunderstandings.
MSMC
thanks dear, regards. @ΦXoce웃Пepeúpa
ΦXocę 웃 Пepeúpa ツ
Got it... I will rephrase that
ΦXocę 웃 Пepeúpa ツ
@MSMC you are welcome
lang-java