需求:
根據List的某個值進行從大到小的排序
代碼如下:
List<Integer> ListData = new ArrayList<>();
ListData.add(1);
ListData.add(2);
ListData.add(3);
ListData.add(4);
Collections.sort(ListData,new Comparator(){
@Override
public int compare(Object o1, Object o2) {
int diff = (Integer)o1 -(Integer) o2;
if (diff>0){
return -1;
}
else if (diff <0){
return 1;
}
else {
return 0;
}
}
});
for (Integer item :ListData){
Log.i("test","item:"+item);
}
輸出結果如下:成功實現了從大到小的排序