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

时间:2025-04-03 22:15:57

方法一: 

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

 

测试:

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

        (mapSortedByKey(param));

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

    static void sortMap(Map<String, String> param) {
        TreeMap<String, String> paramTreeMap = new TreeMap<>(param);
        (paramTreeMap);
    }

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

 

 

相关文章