12. Sort the map according to the value of the key

The map is sorted by the value of the key

//按照key的大小排序,传入map。返回list
private List<JSONObject> sortMap(Map<String, JSONObject> map) {
    List<Map.Entry<String, JSONObject>> list = new  ArrayList<Map.Entry<String,JSONObject>>(map.entrySet());
    Collections.sort(list, new Comparator<Map.Entry<String, JSONObject>>() {
    
    @Override
    public int compare(Map.Entry<String, JSONObject> o1,Map.Entry<String, JSONObject> o2) {
        // 升序排序
        return Integer.parseInt(o1.getKey()) - Integer.parseInt(o2.getKey());
        }
    });
    List<JSONObject> result = new ArrayList<JSONObject>();
    for (Map.Entry<String, JSONObject> entry : list) {
        result.add(entry.getValue());
    }
    return result;
}

Guess you like

Origin blog.csdn.net/yang134679/article/details/131714030