Java:將map集合中的key鍵轉換成小寫、大寫方法


     // main方法運行測試

     public static void main(String[] args) {
 
        Map<String, Object> m3 = new HashMap<String, Object>();
        m3.put("a", "abc");
        m3.put("b", "123");
        m3.put("C", "123");
        m3.put("dD", "123");
 
        Map<String, Object> m4 = new HashMap<String, Object>();
        m4.put("b", "123");
        m4.put("a", "abc");
        m4.put("cDs", "123");
        m4.put("d", "123");
        
        System.out.println("將m4數據的key全部轉換爲大寫===" + transformUpperCase(m4));
        System.out.println("將m3數據的key全部轉換爲小寫===" + transformLowerCase(m4));
 
    }
 
    // 將map值全部轉換爲大寫
    public static Map<String, Object> transformUpperCase(Map<String, Object> orgMap) {
        Map<String, Object> resultMap = new HashMap<>();
        if (orgMap == null || orgMap.isEmpty()) {
            return resultMap;
        }
        Set<String> keySet = orgMap.keySet();
        for (String key : keySet) {
            String newKey = key.toUpperCase();
//            newKey = newKey.replace("_", "");
            resultMap.put(newKey, orgMap.get(key));
        }
        return resultMap;
    }
 
    // 將map值全部轉換爲小寫
    public static Map<String, Object> transformLowerCase(Map<String, Object> orgMap) {
        Map<String, Object> resultMap = new HashMap<>();
        if (orgMap == null || orgMap.isEmpty()) {
            return resultMap;
        }
        Set<String> keySet = orgMap.keySet();
        for (String key : keySet) {
            String newKey = key.toLowerCase();
//            newKey = newKey.replace("_", "");
            resultMap.put(newKey, orgMap.get(key));
        }
        return resultMap;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章