Sorting 如何在Java中从TreeMap中获取排序HashMap
我想按键对hashMap进行排序,需要一些帮助。到目前为止,我所拥有的:Sorting 如何在Java中从TreeMap中获取排序HashMap,sorting,hashmap,Sorting,Hashmap,我想按键对hashMap进行排序,需要一些帮助。到目前为止,我所拥有的: Map<String, Map<String, String>> unsortedMapResult = new HashMap<String, Map<String, String>>(); unsortedMapResult.put("Delete Items", "Before items", "After items"); unsortedMapResult.pu
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>>();
没有“排序HashMap”这样的东西,所以我担心你想要的是根本不可能的。正如上面所说:
此类不保证映射的顺序
以特定的顺序插入元素(这就是您在这里所做的)不会使它们按您想要的顺序出现,其他任何事情也不会发生——除了使用一个集合(比如TreeMap)来代替,该集合尊重元素的某种顺序
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;
Audit Items, Before items, After items
Delete Items, Before items, After items