首先说下需求,在开发中会遇到对List<Object>进行排序,这个也可以在数据库里面查询排序出来,但是有的时候会在查出来之后做一些逻辑处理然后排序,所有就要用到对象排序。
- 首先创建一个类实现Comparator<T> 接口,并重写int compare(T t1, T t2)接口
-
- import java.util.Comparator;
-
-
-
-
- public class ComparatorUtil implements Comparator<ApiCounterResponse> {
-
- public int compare(ApiCounterResponse o1, ApiCounterResponse o2) {
- double tempResult1 = o1.getTempResult();
- double tempResult2 = o2.getTempResult();
- if (tempResult1 > tempResult2) {
- return -1;
- } else if (tempResult1 < tempResult2) {
- return 1;
- } else {
- return 0;
- }
- }
- }
- new一个实现类对象,传地参数需要排序的List对象和Comparator的实现类
-
- public static void main(String[] args) {
- List<ApiCounterResponse> listCounter = new ArrayList<ApiCounterResponse>();
-
- for (int i = 0; i < 10; i ++) {
- ApiCounterResponse api = new ApiCounterResponse();
- api.setMethodId(1L + i);
- api.setTempResult(2.34 + i);
- listCounter.add(api);
- System.out.println(listCounter.get(i).getMethodId());
- }
-
-
- Comparator comp = new ComparatorUtil();
- Collections.sort(listCounter, comp);
-
- for (int i = 0; i < listCounter.size(); i++) {
- System.out.println(listCounter.get(i).getMethodId());
- }
- }