Map map按key值排序

时间:2022-03-22 19:17:42
    private static String buildMd5Params(Map<String, String> map) {
        StringBuilder result = new StringBuilder(256);
        Map<String, String> sortedMap = new TreeMap(new Comparator<String>() {
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);  //按升序排列 ,改为按降序排列return o2.compareTo(o1); 
            }
        });
        sortedMap.putAll(map);
        Map.Entry<String, String> me = null;
        String val = null;
        Iterator it = sortedMap.entrySet().iterator();

        while(it.hasNext()) {
            me = (Map.Entry)it.next();
            val = (String)me.getValue();
            if (val != null) {
                val = val.trim();
                if (!"".equals(val)) {
                    result.append(val);
                }
            }
        }

        return result.toString();
    }
}