I have a List<Map> myList
where each map object has a key, called priority
, and I would like to sort this list by the priority
. I have no idea, how should I manage it.
each map object has a key, called priority
So i guess, the maps keyset contains Strings. Also, if you want to compare the returned value for the priority key, then this object could implement Comparable.
Collections.sort(myList, new Comparator<Map<String,E extends Comparable>>(){
@Override
public int compare(Map<String,E extends Comparable> a, Map<String,E extends Comparable> b){
return a.get("priority").compareTo(b.get("priority"));
//alternative:
//if(a.get("priority").equals(b.get("priority"))return 0;
//if(a.get("priority") > (b.get("priority"))return 1;
//return -1;
}
})
public class MyComparator implements Comparator<Map> { public void compare (Map m1, Map m2) { return ((Integer)m1.get("priority")).compareTo(m2.get("priority"))); } } // ... list.sort(new MyComparator());
如果您不使用整数,则将Integer强制转换为另一个Number子类
If using Java8
myList
.stream()
.sorted((obj1, obj2) -> Integer.compare(obj1.get("Priority"), obj2.get("Priority"))
.collect(Collectors.toList())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.