HashMap按key/value排序

HashMap的key为Date,将其转换为List,并按key排序

Map hm = new HashMap<Date, String>();

主要利用 Comparator这个接口来实现,我这里是排序list里面的时间 分别取到最大的时间和最小的时间。
要实现里面的函数int compare(Object o1, Object o2) 返回一个基本类型的整型,返回负数表示o1 小于o2,返回0 表示o1和o2相等,返回正数表示o1大于o2。

  public class ComparatorDateTest {

    /**
     * @param args
     */
public static void main(String[] args) {
        List list=new ArrayList();
        for (int i = 0; i < 5; i++) {
            Date d=new Date(System.currentTimeMillis()+(int)(Math.random()*1000000000));
            list.add(d);
            System.out.println(d);
        }
        ComparatorDate c=new ComparatorDate();
        Collections.sort(list,c);
        System.err.println(list.get(0));
        System.err.println(list.get(list.size()-1));
    }
}
class Test implements Comparator{
public int compare(Object obj1, Object obj2) {
        Date begin=(Date)obj1;
        Date end=(Date)obj2;
        if(begin.after(end)){
            return 1;
        }
        else{
            return -1;
        }
    }
}

完整程序如下:

public class tradeLinkReducer extends Reducer<Text, Text, Text, Text> {
    public void reduce(Text key,Iterable<Text> values, Context context) throws IOException, InterruptedException{

         /**
          * construct hashmap
          */
         Map hm = new HashMap<Date, String>();
         for (Text  val : values) {  
             String inputValue = val.toString();
             String[] valueData = inputValue.split("\t");
             String dealTimeStr = valueData[10];             
             Date dealTime = parseTime(dealTimeStr);
             hm.put(dealTime, inputValue);
         } 
         /**
          * sort
          */
         List<Map.Entry<Date, String>> infoIds = new ArrayList<Map.Entry<Date, String>>(hm.entrySet());
         Collections.sort(infoIds, new Comparator<Map.Entry<Date, String>>() {   
                public int compare(Map.Entry<Date, String> o1, Map.Entry<Date, String> o2) {      
                    //return (o2.getValue() - o1.getValue()); 
                    Date begin=o1.getKey();  
                    Date end=o2.getKey();  
                    if(begin.after(end)){  
                        return 1;  
                    }  
                    else{  
                        return -1;  
                    }  
                   // return (o1.getKey()).toString().compareTo(o2.getKey());
                }
            }); 

         /**
          * construct outputValue
          */
         StringBuffer outputValue = new StringBuffer();
         int itemNum = infoIds.size();
         outputValue.append(Integer.toString(itemNum)) ;
         for (int i = 0; i < infoIds.size(); i++) {
             outputValue.append("\t"+infoIds.get(i).getValue());
        }         

         /**
          * print the current record
          */
         context.write(key, new Text(outputValue.toString()));
    }

    /**
     * 处理String格式“yyyy/MM/dd HH:mm:ss”或“yyyy/MM/dd”时间为Date格式
     * @param timeStr  需要转换的时间
     * @return outputTime 转换后的时间,格式为Date
     */
    private Date parseTime(String timeStr){
        Date dateTime = null;
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
         if(timeStr.length()<=10){
             timeStr += " 00:00:00";
         }      
         Date outputTime = null;
         try {
             outputTime = formatter.parse(timeStr);             
         } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();                
         }
         return outputTime;
    }
}
阅读更多
换一批

没有更多推荐了,返回首页