How to Lowercase or Uppercase Map Keys in Java
How can we lowercase or uppercase all map keys in Java?
Suppose we’re working with a simple map.
Map<String, Object> map;
1. Lowercase using toLowerCase()
We can lowercase all the map keys by creating a new map.
map.entrySet().stream().collect(
Collectors.toMap(
entry -> entry.getKey().toLowerCase(),
entry -> entry.getValue()
)
);
This will not mutate the original map, so we’ll have to assign this to a new map to use the updated keys.
2. Uppercase using toUpperCase()
We can run through the exact same stream using toUpperCase()
instead of toLowerCase()
.
map.entrySet().stream().collect(
Collectors.toMap(
entry -> entry.getKey().toUpperCase(),
entry -> entry.getValue()
)
);
3. Lowercase/Uppercase nested map
Suppose we’re working with a nested map:
Map<String, Map<String, Object>> nestedMap;
We can simply run the same logic in a nested fashion.
map.entrySet().stream().collect(
Collectors.toMap(
e1 -> e1.getKey().toLowerCase(),
e1 -> e1.getValue().entrySet().stream().collect(
Collectors.toMap(
e2 -> e2.getKey().toLowerCase(),
e2 -> e2.getValue()
)
)
)
);
And of course, we can call toUpperCase()
instead of toLowerCase()
.
Remember to assign the output to a new map in order to use the lowercase or uppercase keys.