java中hashMap的排序

weixin_34120274發表於2016-08-16

hashMap排序,示例:

private void test(){
        Map<String, List<String>> unSupportedDatesMap=new HashMap<String, List<String>>();
        unSupportedDatesMap.put("14:00-18:00", new ArrayList<String>());
        unSupportedDatesMap.put("9:00-12:00", new ArrayList<String>());    
        unSupportedDatesMap.put("19:00-22:00", new ArrayList<String>());
        
        List<Map.Entry<String, List<String>>> intervals =
                new ArrayList<Map.Entry<String, List<String>>>(unSupportedDatesMap.entrySet());
        
        //排序前
        System.out.println("------------------排序前--------------------------");
        for (int i = 0; i < intervals.size(); i++) {
            String id = intervals.get(i).toString();
            System.out.println(id);
        }
        
        //排序
        Collections.sort(intervals, new Comparator<Map.Entry<String, List<String>>>() {   
            public int compare(Map.Entry<String, List<String>> o1, Map.Entry<String, List<String>> o2) { 
                String intervalTime1 = o1.getKey();
                String fromTime1 =intervalTime1.split("-")[0];
                String intervalTime2 = o2.getKey();
                String fromTime2 =intervalTime2.split("-")[0];
                //轉換為分鐘值
                String hour1=fromTime1.split(":")[0].trim();
                String mininute1=fromTime1.split(":")[1].trim();
                int times1=60*Integer.parseInt(hour1)+Integer.parseInt(mininute1);
                
                String hour2=fromTime2.split(":")[0].trim();
                String mininute2=fromTime2.split(":")[1].trim();
                int times2=60*Integer.parseInt(hour2)+Integer.parseInt(mininute2);                
                return (times1 - times2);                 
            }
        }); 
        
        //排序後
        System.out.println("------------------排序後--------------------------");
        for (int i = 0; i < intervals.size(); i++) {
            String id = intervals.get(i).toString();
            System.out.println(id);
        }
    }

 

相關文章