I have the following Map:
Map<Long, List<Address>> map = new HashMap<Long, List<Address>>();
which is filled with pairs of keys and values. For example: key = student id and
value = list of Address. In Address object I have country name(String). I want to sort the total map by the country name. I have tried many ways but not getting the Idea. Any ideas? Below is my tried code.
private static Map<Long, List<Address>> sortByValue(Map<Long, List<Address>> unsortMap) {
// Convert Map to List of Map
List<Map.Entry<Long, List<Address>>> unSortedList =
new ArrayList<Map.Entry<Long, List<Address>>>(unsortMap.entrySet());
// sort the List
Collections.sort(unSortedList, new Comparator<Map.Entry<Long, List<Address>>>() {
public int compare(Map.Entry<Long, List<Address>> object1,
Map.Entry<Long, List<Address>> object2) {
// sort by country name
return ???;
}
});
// Loop the sorted list and put it into a new insertion order Map LinkedHashMap
Map<Long, List<Address>> sortedMap = new LinkedHashMap<Long, List<Address>>();
for (Map.Entry<Long, List<Address>> entry : unSortedList) {
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}