Reputation: 979
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?
Upvotes: 0
Views: 2185
Reputation: 2122
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());
}
Upvotes: 6