Java将Hashmap放入Treemap中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19512850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 17:54:15  来源:igfitidea点击:

Java putting Hashmap into Treemap

javahashmaptreemap

提问by BeyondProgrammer

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

我目前正在从文本文件中读取 200 万行,如上一个问题 Java Fastest way to read through text file with 200万行

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?

现在我将这些信息存储到 HashMap 中,我想通过 TreeMap 对其进行排序,因为我想使用天花板键。以下方法是否正确?

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

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

采纳答案by Akkusativobjekt

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

Should work anyway.

无论如何都应该工作。

回答by husayt

This would work just fine:

这将工作得很好:

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

But I wouldn't advise using HashMapto store the input. You end up with two Maps holding the same huge data. Either do it on the fly and add directly into TreeMapor use Listto TreeMapconversion.

但我不建议使用HashMap来存储输入。您最终会得到两个包含相同庞大数据的 Map。无论是做对飞,并直接加入到TreeMap或使用ListTreeMap的转换。

Also, for even more efficiency consider primitive collections.

此外,为了提高效率,请考虑使用原始集合

回答by Nagmani Verma

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

在添加到 Treemap 之前,HashMap 将允许 null 但 TreeMap 不允许,从键集中删除 null