在java中,如果要對集合對像或數組對象進行排序,需要實現Comparator接口以達到我們想要的目標。
接下來我們模擬下在集合對像中對日期屬性進行排序
一、實體類Step
package com.ljq.entity;/** * 運號單流程* * @author Administrator * */public class Step{ /** 處理時間*/ private String acceptTime = ""; /** 快件所在地點*/ private String acceptAddress = ""; public Step() { super(); } public Step(String acceptTime, String acceptAddress) { super(); this.acceptTime = acceptTime; this.acceptAddress = acceptAddress; } public String getAcceptTime() { return acceptTime; } public void setAcceptTime(String acceptTime) { this.acceptTime = acceptTime; } public String getAcceptAddress() { return acceptAddress; } public void setAcceptAddress(String acceptAddress) { this.acceptAddress = acceptAddress; }}
二、實現Comparator接口
package com.ljq.entity;import java.util.Comparator;import java.util.Date;import com.ljq.util.UtilTool;/** * 對Step類進行排序* * @author Administrator * */public class StepComparator implements Comparator<Step>{ /** * 如果o1小於o2,返回一個負數;如果o1大於o2,返回一個正數;如果他們相等,則返回0; */ @Override public int compare(Step o1, Step o2 ) { Date acceptTime1=UtilTool.strToDate(o1.getAcceptTime(), null); Date acceptTime2=UtilTool.strToDate(o2.getAcceptTime(), null); //對日期字段進行升序,如果欲降序可採用before方法if (acceptTime1.after(acceptTime2)) return 1; return -1; }}
三、測試
package junit;import java.util.Collection;import java.util.Collections;import java.util.List;import org.junit.Test;public class StepComparatorTest { @Test public void sort() throws Exception{ List<Step> steps =new ArrayList<Step>; //對集合對象進行排序StepComparator comparator=new StepComparator(); Collections.sort(steps, comparator); if(steps!=null&&steps.size()>0){ for(Step step: steps){ System.out.println(step.getAcceptAddress()); System.out.println(step.getAcceptTime()); } } }}