How to Sort a List of Maps by two Categories?

℡╲_俬逩灬. 提交于 2019-12-12 03:14:14

问题


I have a List of maps, in which I have two categories "foo" and "bar"! With my function now, I can Iterate it and sort by foo with this:

public List<Map<String, Object>> makeAllSkillsMaps(List<Stuff> li) {
    List<Map<String, Object>> l = new LinkedList<Map<String, Object>>();
    List<Skill> w_l = li;
    for (Stuff stuff : w_l) {
        Map<String, Object> r_m = new HashMap<String, Object>();
        r_m.put("ID", stuff.getID());
        r_m.put("Bar", stuff.getBar());
        r_m.put("Foo", stuff.getFoo());
        l.add(r_m);
    }
    Comparator<Map<String, Object>> mapComparator = new Comparator<Map<String, Object>>() {
        public int compare(Map<String, Object> m2, Map<String, Object> m1) {
            return ((String) m1.get("Foo").toString()).compareTo((String) m2.get("Foo").toString());
        }
    };
    l.sort(mapComparator);
    return l;
}

Is there an elegant way to sort this by two categorys, so I have it first sortet by Foo, and then by Bar:

   Foo   |   Bar   |   ID        
============================
 A       | 1       | 922
 A       | 2       | 726
 B       | 5       | 121
 B       | 98      | 654
 G       | 1       | 823
 G       | 7       | 324

回答1:


It's rather obvious, actually. If there is no difference in your first criterion, you go on to the second one.

On second inspection, I have no idea why you're casting the result of toString() to a String.

public int compare(Map<String, Object> m2, Map<String, Object> m1) {
    int cmp = m1.get("Foo").toString().compareTo(m2.get("Foo").toString());
    if (cmp == 0) {
        return m1.get("Bar").toString().compareTo(m2.get("Bar").toString());
    }
    return cmp;
}


来源:https://stackoverflow.com/questions/28474709/how-to-sort-a-list-of-maps-by-two-categories

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!