Sort a HashMap inside a Map based on value

霸气de小男生 提交于 2019-12-13 04:46:07

问题



I am trying to sort a hashmap based on alphabetical value which itself is stored inside another Map.

The structure looks like: Map<String, HashMap<String, String>>

I want to sort this Map based on the value of the HashMap inside so all in all the full map will be sorted so as the HashMap based on the HashMap's value.

-- UPDATE:

For example if I have something like:

Map: abc Value: HashMap[EN, a]
Map: xyz Value: HashMap[DE, c]
Map: pqr Value: HashMap[PL, b]

then after sort it should be something like:

Map: abc Value: HashMap[EN, a]
Map: pqr Value: HashMap[PL, b]
Map: xyz Value: HashMap[DE, c]

How to proceed?


回答1:


Sorting on the value may be a bad idea, because it would suppose that sort becomes incorrect if you change what's in the value map.

If you really want to sort according to the value, then you need to create another map:

final Map<String, Map<String, String>> map= new HashMap<>();

Map<String, String> map1 = new HashMap<>();
map1.put("EN", "a");
Map<String, String> map2 = new HashMap<>();
map2.put("DE", "c");
Map<String, String> map3 = new HashMap<>();
map3.put("PL", "b");

map.put("abc", map1);
map.put("xyz", map2);
map.put("pqr", map3);

TreeMap<String, Map<String, String>> sorted = new TreeMap<>(new Comparator<String>() {

    @Override public int compare(String s1, String s2) {
        String value1 =  map.get(s1).values().iterator().next();
        String value2 =  map.get(s2).values().iterator().next();

        return value1.compareTo(value2);
    }
});
sorted.putAll(map);

for(Map.Entry<String, Map<String, String>> e : sorted.entrySet()) {
    System.out.println(e.getKey());
}



回答2:


If you want the sorted map based on alphabetical value, then you can use TreeMap. TreeMap is sorted map, means that the order of the keys can be sorted, and when iterating over the keys.

TreeMap<String, HashMap<String,String>> map = new TreeMap<String, HashMap<String,String>>();

Then Sort the value using the Comparator interface.



来源:https://stackoverflow.com/questions/33275195/sort-a-hashmap-inside-a-map-based-on-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!