Java putting Hashmap into Treemap

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-18 04:39:14

问题


I am currently reading 2 million lines from a textfile as asked in the previous question Java Fastest way to read through text file with 2 million lines

Now I store these information into HashMap and I want to sort it via TreeMap because I want to use ceilingkey. Is the following method correct?

private HashMap<Integer, String> hMap = new HashMap();

private TreeMap<Integer, String> tMap = new TreeMap<Integer, String>(hMap);

回答1:


HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>();
treeMap.putAll(hashMap);

Should work anyway.




回答2:


This would work just fine:

HashMap<Integer, String> hashMap = new HashMap<>();
TreeMap<Integer, String> treeMap = new TreeMap<>(hashMap);

But I wouldn't advise using HashMap to store the input. You end up with two Maps holding the same huge data. Either do it on the fly and add directly into TreeMap or use List to TreeMap conversion.

Also, for even more efficiency consider primitive collections.




回答3:


HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>();
hashMap.remove(null);
treeMap.putAll(hashMap);

HashMap will allow null but TreeMap not so before adding into Treemap, remove null from keyset



来源:https://stackoverflow.com/questions/19512850/java-putting-hashmap-into-treemap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!