【问题标题】:Java putting Hashmap into TreemapJava将Hashmap放入Treemap
【发布时间】:2013-10-31 00:39:03
【问题描述】:

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

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

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

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

【问题讨论】:

  • Collections.sort(hMap) ? ,Collections.sort(hMap,WITH_MY_OWN_COMPARATOR) ?
  • 为什么不直接把它放到TreeMap 中呢?为什么要多走一步?
  • hrm...我还是更喜欢用树形图对其进行排序,但就我的代码而言,树形图是空的
  • @suresh atta : Collections.sort(hMap) 不起作用,sort() 仅适用于列表

标签: java hashmap treemap


【解决方案1】:
HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>();
treeMap.putAll(hashMap);

无论如何都应该工作。

【讨论】:

  • 你在开玩笑吗??? Passing constructor also callsputAll() :)。查看源代码链接,我添加了
  • @user2822351 我不是说这个答案是错误的,我要说的是这个答案等于你现在正在做的事情。
  • 没错,但是构造函数的使用更加优雅。
  • @user2822351问题是......它与您在上面的问题中发布的内容有什么不同!?
  • @Akkusativobjekt,我正在使用构造函数,但它不起作用。当我尝试打印时树形图为空
【解决方案2】:

这样就可以了:

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

但我不建议使用HashMap 来存储输入。您最终会得到两个拥有相同庞大数据的地图。要么即时执行,然后直接添加到 TreeMap 或使用 ListTreeMap 转换。

另外,为了提高效率,请考虑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 将允许 null 但 TreeMap 在添加到 Treemap 之前不允许,从 keyset 中删除 null

    【讨论】:

      猜你喜欢
      • 2021-01-21
      • 1970-01-01
      • 1970-01-01
      • 2012-05-03
      • 1970-01-01
      • 1970-01-01
      • 2021-04-29
      • 2012-01-13
      • 2013-01-12
      相关资源
      最近更新 更多