1. 程式人生 > >java 物件比較器重寫Comparator

java 物件比較器重寫Comparator

//此處省略pojo實現
    Students s1 = new Students("1001", "2015-10-26", "2");
    Students s2 = new Students("1001", "2016-09-26", "1");
    Students s3 = new Students("1001", "2016-10-17", "3");
    Students s4 = new Students("1001", "2016-06-16", "3");
    Students s5 = new Students("1001", "2016-08-13", "3");
    Students s6 = new 
Students("1002", "2016-06-12", "1"); Students s7 = new Students("1003", "2016-06-12", "1"); List<Students> listSort = new ArrayList<Students>(); listSort.add(s1); listSort.add(s2); listSort.add(s3); listSort.add(s4); listSort.add(s5); listSort.add(s6); listSort.add(s7);
// 實現內部匿名方法
    Collections.sort(listSort, new Comparator<Students>() {
        @Override
public int compare(Students s1, Students s2) {
          //如果學生編號相同,比較學生名次
            if (s1.getCouponId().equals(s2.getCouponId())) {
          //
                if (s1.getCouponlist().equals(s2.getCouponlist())) {
                    return 
s1.getCouponSt().compareTo(s2.getCouponSt()); } else {
          //如果學生名次相同,比較入學時間
                    return s1.getCouponlist().compareTo(s2.getCouponlist());
                }
            } else {
          //如果學編號不同,按編號進行排序
                return s1.getCouponId().compareTo(s2.getCouponId());
            }
        }
    });

    for (int i = 0; i < listSort.size(); i++) {
        System.out.println(listSort.get(i));
    }
}
HashMap基於values排序重寫:
基本思路還是重寫方法Collections,把HashMap的值儲存到List當中
public static void sortMapByValues(Map<String, String> hmap) {
    Set<Map.Entry<String, String>> mapEntries = hmap.entrySet();

    List<Map.Entry<String, String>> entryList = new LinkedList<Map.Entry<String, String>>(mapEntries);

    Collections.sort(entryList, new Comparator<Map.Entry<String, String>>() {
        @Override
public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
            return o1.getValue().compareTo(o2.getValue());
        }
    });

    Map<String, String> newMap = new LinkedHashMap<String, String>();

    for (Map.Entry<String, String> entry : entryList) {
        System.out.println(entry.getKey() + "--" + entry.getValue());
    }
}