根据值对Map中的HashMap进行排序 [英] Sort a HashMap inside a Map based on value

查看:275
本文介绍了根据值对Map中的HashMap进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我正在尝试根据字母值对哈希图进行排序,而哈希值本身存储在另一个Map中.


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

结构如下: Map<String, HashMap<String, String>>

我想基于内部HashMap的值对该Map进行排序,因此所有完整地图中的所有内容都将按照HashMap的值进行排序,从而像HashMap一样进行排序.

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.

- 更新:

例如,如果我有类似的内容:

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]

如何进行?

推荐答案

对值进行排序可能不是一个好主意,因为如果您更改值映射中的内容,它将认为排序不正确.

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());
}

这篇关于根据值对Map中的HashMap进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆