List自定义排序(可多条件)

时间:2022-02-17 14:34:20

1:先建需要排序的属性Model

 package com.msqsoft.app.queuing.util;

 public class ListOrderByModel {

     private String queueNumber;

     private Integer status;

     public String getQueueNumber() {
return queueNumber;
} public void setQueueNumber(String queueNumber) {
this.queueNumber = queueNumber;
} public Integer getStatus() {
return status;
} public void setStatus(Integer status) {
this.status = status;
} public ListOrderByModel(String queueNumber, Integer status){
this.queueNumber = queueNumber;
this.status = status;
}
}

2:建立排序 Util 定义排序方式 需实现 Comparator

 package com.msqsoft.app.queuing.util;

 import java.util.Comparator;

 public class ListOrderByComparatorModelUtil implements Comparator {

     @Override
public int compare(Object obj1, Object obj2) { ListOrderByModel orderByModel1 = (ListOrderByModel)obj1;
ListOrderByModel orderByModel2 = (ListOrderByModel)obj2; // 先排序status
if (orderByModel1.getStatus() > orderByModel2.getStatus()) {
return -1;
} else if (orderByModel1.getStatus() < orderByModel2.getStatus()) {
return 1;
} else {
// 排序号码
return orderByModel1.getQueueNumber().compareTo(orderByModel2.getQueueNumber());
}
} }

3 : 测试

 package web;

 import java.text.Collator;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List; import com.msqsoft.app.queuing.util.ListOrderByComparatorModelUtil;
import com.msqsoft.app.queuing.util.ListOrderByModel; public class Test1 {
@SuppressWarnings("unchecked")
public static void main(String[] args) throws ParseException { List list = new ArrayList();
list.add(new ListOrderByModel("A002", 0));
list.add(new ListOrderByModel("A001", 0));
list.add(new ListOrderByModel("A003", 0));
list.add(new ListOrderByModel("A006", 6));
list.add(new ListOrderByModel("A004", 0));
list.add(new ListOrderByModel("A008", 5));
list.add(new ListOrderByModel("A005", 0));
list.add(new ListOrderByModel("A007", 6)); ListOrderByComparatorModelUtil comparator = new ListOrderByComparatorModelUtil();
Collections.sort(list, comparator);
for (int i = 0; i < list.size(); i++) {
ListOrderByModel listMode = (ListOrderByModel) list.get(i);
System.out.println(listMode.getStatus() + "," + listMode.getQueueNumber());
}
}
}