Java初学习---Comparator的用法

在java中,如果要对集合对象或数组对象进行排序,需要实现Comparator接口以达到我们想要的目标。

 接下来我们模拟下在集合对象中对日期属性进行排序

 一、实体类Step

package com.ljq.entity;
//... ...
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;
// ...
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());
            }
        }

    }
}



你可能感兴趣的:(Java初学习---Comparator的用法)