1.针对基本数据类型的list集合进行排序
这种相对来说比较简单,主要用于List<Integer> sortList 、List<Double> sortList等等
Collections.sort(sortList);该方法为默认升序
如果要降序,可改为:Collections.sort(testList,Collections.reverseOrder());
2.针对实体类bean集合进行排序
一种方式是该bean需要实现Comparable接口
public class DefectTaskModel implements Comparable<DefectTaskModel> {
/**
* 缺陷位置
*/
private double defectPosition;
public double getDefectPosition() {
return defectPosition;
}
public void setDefectPosition(double defectPosition) {
this.defectPosition = defectPosition;
}
@Override//在这里决定是按照缺陷位置升序还是降序,此处是升序
public int compareTo(DefectTaskModel o) {
double i = this.getDefectPosition() - o.getDefectPosition();
if (i > 0) {
return 1;
} else {
return -1;
}
}
}
使用方式:Collections.sort(beanList);
还有一种就是直接写在代码里,不改动实体类
Collections.sort(mList, new Comparator<NewsBean>() {
//调用sort()方法,并实现Comparator接口中的compare()方法
@Override
public int compare(NewsBean lhs, NewsBean rhs) {
int value = Integer.valueOf(rhs.getId())
- Integer.valueOf(lhs.getId());
Log.e("降序排序---------------》", "" + value);
return value;
}
});
升序排序:
Collections.sort(mList, new Comparator<NewsBean>() {//调用sort()方法,并实现Comparator接口中的compare()方法
@Override
public int compare(NewsBean lhs, NewsBean rhs) {
int value = Integer.valueOf(lhs.getId())
-Integer.valueOf(rhs.getId());
Log.e("升序排序---------------》", "" + value);
return value;
}
});