Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting List of objects in android [duplicate]

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.

like image 818
MSMC Avatar asked Dec 10 '22 17:12

MSMC


1 Answers

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());
    }

});
like image 149
ΦXocę 웃 Пepeúpa ツ Avatar answered Jan 14 '23 14:01

ΦXocę 웃 Пepeúpa ツ