Lowercase all HashMap keys

前端 未结 4 1244
夕颜
夕颜 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:27

    the concerns in the above answers are correct and you might need to reconsider changing the data structure you are using.

    for me, I had a simple map I needed to change its keys to lower case

    take a look at my snippet, its a trivial solution and bad at performance

    private void convertAllFilterKeysToLowerCase() {
        HashSet keysToRemove = new HashSet();
        getFilters().keySet().forEach(o -> {
            if(!o.equals(((String) o).toLowerCase()))
                keysToRemove.add(o);
        });
        keysToRemove.forEach(o -> getFilters().put(((String) o).toLowerCase(), getFilters().remove(o)));
    }
    

提交回复
热议问题