Java Map中数据按照key进行排序

方法一:

static String mapSortedByKey(Map param) {
        StringBuilder stringBuilder = new StringBuilder();
        ArrayList keyList = new ArrayList<>(param.keySet());
        Collections.sort(keyList);
        for (int i = 0; i < keyList.size(); i++) {
            String key = keyList.get(i);
            if (i == keyList.size() - 1) {
                stringBuilder.append(key).append("=").append(param.getOrDefault(key, ""));
            } else {
                stringBuilder.append(key).append("=").append(param.getOrDefault(key, "")).append("&");
            }
        }
        return stringBuilder.toString();
    }

测试:

Map param = new HashMap<>();
        param.put("type", "1");
        param.put("user_mobile", "2");
        param.put("full_name", "3");
        param.put("id_no", "4");
        param.put("secret", "5");

        System.out.println(mapSortedByKey(param));

方法二:使用treeMap直接变为有序的map

    static void sortMap(Map param) {
        TreeMap paramTreeMap = new TreeMap<>(param);
        System.out.println(paramTreeMap);
    }

    public static void main(String[] args) {
        HashMap paramHashMap = new HashMap() {
            {
                put("type", "1");
                put("user_mobile", "2");
                put("full_name", "3");
                put("id_no", "4");
                put("secret", "5");
            }
        };
        sortMap(paramHashMap);
    }

你可能感兴趣的:(java,java,算法,数据结构,大数据,开发语言)