See Collections#sort(List<T> list)
. It helps you to sort any list of T
which implements Comparable.
If your class does not implement Comparable, you can provide a Comparator and call static void <T> sort(List<T> list, Comparator<? super T> c)
.
Example with a small class:
public class Item implements Comparable<Item>{
private Integer number;
private Double distance;
//Getters & Setters
...
@Override
public int compareTo(Item o) {
return this.distance > o.distance? -1 : 1;
}
}
As it implements Comparable, you can sort a list like this :
List<Item> myItemList = ... ;
Collections.sort(myItemList);
//Now, myItemList is sorted
OR you can provide a Comparator to sort items on any criteria :
List<Item> list = ...;
//Here, I provide a Comparator to sort Items by number.
Collections.sort(list, new Comparator<Item>() {
@Override
public int compare(Item o1, Item o2) {
return o2.getNumber() - o1.getNumber();
}
});