如何从Java中的TreeMap中获取排序的HashMap

时间:2016-04-13 10:44:59

标签: sorting hashmap

我想按键对hashMap进行排序,需要一些帮助。到目前为止我所拥有的:

Map<String, Map<String, String>> unsortedMapResult = new HashMap<String, Map<String, String>>(); 

unsortedMapResult.put("Delete Items", "Before items", "After items");
unsortedMapResult.put("Audit Items", "Before items", "After items");

Map<String, Map<String, String>> treeMapResult = new TreeMap<String, 
Map<String, String>>(unsortedMapResult);

Map<String, Map<String, String>> finalResult = new HashMap<String, Map<String, String>>();

我只是走过TreeMap并将内容复制到新的HashMap

Set<Entry<String, Map<String, String>>> entrySets = treeMapResult.entrySet();

for (Entry<String, Map<String, String>> ent : entrySets) {
  finalResult.put(ent.getKey(), ent.getValue());
}

return finalResult;

问题是finalResult现在没有排序,与我最初的unsortedMapResult完全相同。

我想拥有它,以便按照以下方式排序:

Audit Items, Before items, After items
Delete Items, Before items, After items

1 个答案:

答案 0 :(得分:0)

没有这样的东西作为“排序的HashMap”,所以我担心你要求的东西根本不可能。正如the documentation for HashMap所说:

  

此课程不保证地图的顺序

以特定的顺序插入元素(这是你在这里做的)将无法按照你想要的顺序出现它们,除了使用一个集合(比如TreeMap)之外别无其他任何东西确实尊重元素的某种排序。

相关问题