java 对象比较器重写Comparator

来源:互联网 发布:定态薛定谔方程 知乎 编辑:程序博客网 时间:2024/06/07 04:45
//此处省略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());    }}

                                             
0 0
原创粉丝点击