【问题标题】:How to convert HashMap to TreeMap如何将 HashMap 转换为 TreeMap
【发布时间】:2017-03-16 17:51:24
【问题描述】:

这个问题似乎很受欢迎,但我无法为我的实施获得正确的结果。我以thread 为例,但到目前为止还没有运气。

这里我有 HashMap,我需要将其转换为 TreeMap 以便对键值进行排序:

HasMap<String, HashMap<String, SomeBean>> hashMap = (HashMap<String, HashMap<String, SomeBean>>)request.getAttribute("HASHMAP");

应用迭代器后,我可以看到未排序的结果。

现在我想把它转换成 TreeMap:

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

结果:

The constructor TreeMap<String,TreeMap<String,SomeBean>>(HashMap<String,HashMap<String,SomeBean>>) is undefined

好吧,似乎是因为我的 bean 类嵌套了地图,所以它不允许我创建新的树形地图。这是可以理解的,因为我不希望 TreeMap 有适合我的标准的构造函数,但问题是我如何找到解决这个问题的方法?

【问题讨论】:

  • 嵌套类必须是特定的HashMapTreeMap,还是可以是通用接口Map
  • 你试过了吗 treeMap.putAll(hashMap); ? repl.it/GZO1/0
  • @nandsito 后端将其作为 HashMap 并作为属性传递到前端,如果我更改后端最好将其更改为 TreeMap,我只是不想触摸后端,因为它已经开发了由另一位开发人员尝试在 jsp 页面中找到解决方案。
  • @K.S 我做到了,如果你有原始值或字符串作为参数,它可以工作,但正如我所说,如果我的 bean 类有嵌套映射,它会给我错误。

标签: java hashmap treemap


【解决方案1】:

如果您的代码使用嵌套映射作为常规Map,即它不使用HashMapTreeMap 中定义的任何特定方法,您可以使用Map 来定义变量的类型参数:

HashMap<String, Map<String, SomeBean>> hashMap =
    (HashMap<String, Map<String, SomeBean>>) request.getAttribute("HASHMAP");

TreeMap<String, Map<String, SomeBean>> treeMap =
    new TreeMap<String, Map<String, SomeBean>>(hashMap);

否则,您将无法使用constructor(Map)putAll(Map),您必须手动填写treeMap

【讨论】:

    【解决方案2】:

    由于您的地图具有不兼容的值类型,您需要手动转换它们:

        Map<String, Map<String, SomeBean>> treeMap = new TreeMap<>();
        for (Map.Entry<String, HashMap<String, Integer>> e : hashMap.entrySet())
            treeMap.put(e.getKey(), new TreeMap<>(e.getValue()));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-16
      • 1970-01-01
      • 1970-01-01
      • 2016-02-09
      • 2020-06-11
      • 1970-01-01
      相关资源
      最近更新 更多