小写所有HashMap键 [英] Lowercase all HashMap keys

查看:186
本文介绍了小写所有HashMap键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一种情况,我想小写HashMap的所有键(不要问为什么,我只需要这样做). HashMap有数百万个条目.

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.

起初,我以为我会创建一个新的Map,遍历要小写的map条目,然后添加相应的值.该任务每天应该只运行一次或类似的操作,所以我认为我可以裸露它.

At first, I thought I 'd just create a new Map, iterate over the entries of the map that is to be lowercased, and add the respective values. This task should run only once per day or something like that, so I thought I could bare this.

Map<String, Long> lowerCaseMap = new HashMap<>(myMap.size());
for (Map.Entry<String, Long> entry : myMap.entrySet()) {
   lowerCaseMap.put(entry.getKey().toLowerCase(), entry.getValue());
}

但是,这一次导致我要复制地图的服务器超载时,导致了一些OutOfMemory错误.

this, however, caused some OutOfMemory errors when my server was overloaded during this one time that I was about to copy the Map.

现在我的问题是,如何以最小的内存占用空间完成此任务?

Now my question is, how can I accomplish this task with the smallest memory footprint?

小写字母后是否要删除每个键-已添加到新的地图帮助中?

Would removing each key after lowercased - added to the new Map help?

我可以利用java8流来使其更快吗? (例如这样的东西)

Could I utilize java8 streams to make this faster? (e.g something like this)

Map<String, Long> lowerCaseMap = myMap.entrySet().parallelStream().collect(Collectors.toMap(entry -> entry.getKey().toLowerCase(), Map.Entry::getValue));

更新 看来这是Collections.unmodifiableMap,所以我没有选择

Update It seems that it's a Collections.unmodifiableMap so I don't have the option of

小写字母后删除每个键-添加到新的地图

removing each key after lowercased - added to the new Map

推荐答案

除了使用HashMap,您还可以尝试使用不区分大小写的TreeMap.这样可以避免为每个密钥创建小写版本:

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<String, Long> map = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
map.putAll(myMap);

构造完此映射后,put()get()的行为将不区分大小写,因此您可以使用全小写键保存和获取值.遍历键将以其原始的(可能是大写的)形式返回它们.

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<String, ?> get and put ignoring case?

这篇关于小写所有HashMap键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆