首页 > 代码库 > java自定义类型 比较排序 Comparator接口

java自定义类型 比较排序 Comparator接口

String service_time = "6:00:00,7:00:00,8:00:00,9:00:00,10:00:00,11:00:00,12:00:00,13:00:00,14:00:00,15:00:00,16:00:00,17:00:00,18:00:00,19:00:00,20:00:00,21:00:00,22:00:00
";
List<String> list = StringUtil.stringToList(service_time, ",");
StringTimeSort sort = new StringTimeSort();  
Collections.sort(list,sort);
package com.enation.eop.sdk.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Comparator;

public class StringTimeSort implements Comparator{

    @Override
    public int compare(Object arg0, Object arg1) {
        // TODO Auto-generated method stub
        String time0 = (String) arg0;
        String time1 = (String) arg1;
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); 
        int t0 = 0;  
        int t1 = 0;
        try {
            t0 = (int) sdf.parse(time0).getTime();
            t1 = (int) sdf.parse(time1).getTime();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        return t0 > t1 ? 1 : -1; //按照时间的由小到大排列 
    }

}
通过实现Comparator接口 完成自定义排序

java自定义类型 比较排序 Comparator接口