Java中实现Comparator接口和用法实例(简明易懂)
在java中,如果要对集合对象或数组对象进行排序,需要实现Comparator接口以达到我们想要的目标。
接下来我们模拟下在集合对象中对日期属性进行排序
一、实体类Step
packagecom.ljq.entity; /** *运号单流程 * *@authorAdministrator * */ publicclassStep{ /**处理时间*/ privateStringacceptTime=""; /**快件所在地点*/ privateStringacceptAddress=""; publicStep(){ super(); } publicStep(StringacceptTime,StringacceptAddress){ super(); this.acceptTime=acceptTime; this.acceptAddress=acceptAddress; } publicStringgetAcceptTime(){ returnacceptTime; } publicvoidsetAcceptTime(StringacceptTime){ this.acceptTime=acceptTime; } publicStringgetAcceptAddress(){ returnacceptAddress; } publicvoidsetAcceptAddress(StringacceptAddress){ this.acceptAddress=acceptAddress; } }
二、实现Comparator接口
packagecom.ljq.entity; importjava.util.Comparator; importjava.util.Date; importcom.ljq.util.UtilTool; /** *对Step类进行排序 * *@authorAdministrator * */ publicclassStepComparatorimplementsComparator<Step>{ /** *如果o1小于o2,返回一个负数;如果o1大于o2,返回一个正数;如果他们相等,则返回0; */ @Override publicintcompare(Stepo1,Stepo2){ DateacceptTime1=UtilTool.strToDate(o1.getAcceptTime(),null); DateacceptTime2=UtilTool.strToDate(o2.getAcceptTime(),null); //对日期字段进行升序,如果欲降序可采用before方法 if(acceptTime1.after(acceptTime2))return1; return-1; } }
三、测试
packagejunit; importjava.util.Collection; importjava.util.Collections; importjava.util.List; importorg.junit.Test; publicclassStepComparatorTest{ @Test publicvoidsort()throwsException{ List<Step>steps=newArrayList<Step>; //对集合对象进行排序 StepComparatorcomparator=newStepComparator(); Collections.sort(steps,comparator); if(steps!=null&&steps.size()>0){ for(Stepstep:steps){ System.out.println(step.getAcceptAddress()); System.out.println(step.getAcceptTime()); } } } }