How can I LowerCase all the HashMap's values?

nadineDinDin :

I have a Map<String,Map<String,String>> where I'd like to LowerCase every key and value. With the following code, I'm able to do so but the structure of my data changes. How can I possibly fix this?

for (Map.Entry<String, Map<String, String>> t : list.entrySet()) {
    for (Map.Entry<String, String> e : t.getValue().entrySet()) {
        lowerCaseList1.put(t.getKey().toLowerCase().trim(), lowerCaseList2.put(e.getValue().toLowerCase().trim(), e.getKey().toLowerCase().trim()));
    }
}
Andreas :

To convert all 3 strings in a Map<String,Map<String,String>> to uppercase1, create a new map.

Map<String,Map<String,String>> input = Map.of("abc", Map.of("Def", "Ghi"),
                                              "jkl", Map.of("MNO", "PQR", "stu", "vwx"));

Map<String,Map<String,String>> output = input.entrySet().stream()
        .collect(Collectors.toMap(
                e1 -> e1.getKey().toUpperCase(),
                e1 -> e1.getValue().entrySet().stream().collect(Collectors.toMap(
                        e2 -> e2.getKey().toUpperCase(),
                        e2 -> e2.getValue().toUpperCase()))));

System.out.println(input);
System.out.println(output);

Output

{abc={Def=Ghi}, jkl={stu=vwx, MNO=PQR}}
{ABC={DEF=GHI}, JKL={STU=VWX, MNO=PQR}}

Note: The code will fail with IllegalStateException: Duplicate key if there are 2 keys that will become the same when uppercased.

Map<String,Map<String,String>> input = Map.of("aaa", Map.of("bbb", "ccc", "Bbb", "Ccc"));

Output

java.lang.IllegalStateException: Duplicate key BBB (attempted merging values CCC and CCC)

1) Question originally asked for uppercase, but has since been changed to ask for lowercase. Leaving answer unchanged, since it doesn't really matter for the purpose of showing how to change casing.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=27002&siteId=1