将HashMap放入TreeMap中的Java操作

16

我目前正在阅读一个文本文件,其中有200万行,这是之前问题中提到的: Java Fastest way to read through text file with 2 million lines

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

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

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

1
Collections.sort(hMap)Collections.sort(hMap,WITH_MY_OWN_COMPARATOR) - Suresh Atta
4
为什么不直接将其放入“TreeMap”中?为什么要多此一举? - Stewart
嗯...我仍然更喜欢使用TreeMap进行排序,但就我的代码而言,TreeMap是空的。 - BeyondProgrammer
@suresh atta:Collections.sort(hMap) 不起作用,sort() 只能用于 List。 - Kushal
3个回答

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

应该无论如何都能工作。


3
你是在开玩笑吗?传递构造函数也会调用 putAll() 方法 :)。请查看源代码链接,我已经添加了。 - Suresh Atta
@user2822351 我并不是在说这个答案是错的,我想表达的是这个答案和你现在正在做的事情是一样的。 - Suresh Atta
2
这是正确的,但构造函数的使用更加优雅。 - Akkusativobjekt
问题是...它与您在上面的问题中发布的是否有任何不同!? - codeMan
@sᴜʀᴇsʜ ᴀᴛᴛᴀ 哦,天哪,我终于解决了它,因为哈希映射是在运行时添加的,所以我必须在将其添加到哈希映射后构造它。 - BeyondProgrammer
显示剩余3条评论

6

这将完美地工作:

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

但是我不建议使用HashMap来存储输入。这样会导致两个Map保存相同的大量数据。要么即时处理并直接添加到TreeMap中,要么使用List进行TreeMap转换。

此外,为了更高效,考虑使用原始类型集合


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

HashMap允许null,但TreeMap不允许。因此,在添加到TreeMap之前,请从keyset中删除null。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接