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