Lowercase all HashMap keys

前端 未结 4 1246
夕颜
夕颜 2021-02-12 14:17

I \'ve run into a scenario where I want to lowercase all the keys of a HashMap (don\'t ask why, I just have to do this). The HashMap has some millions of entries.

At fir

4条回答
  •  太阳男子
    2021-02-12 14:33

    Instead of using HashMap, you could try using a TreeMap with case-insensitive ordering. This would avoid the need to create a lower-case version of each key:

    Map map = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
    map.putAll(myMap);
    

    Once you've constructed this map, put() and get() will behave case-insensitively, so you can save and fetch values using all-lowercase keys. Iterating over keys will return them in their original, possibly upper-case forms.

    Here are some similar questions:

    • Case insensitive string as HashMap key
    • Is there a good way to have a Map get and put ignoring case?

提交回复
热议问题