Make the first map as TreeMap and for the second Map, sort it by values. Refer this post
Below is the code snippet for your problem.
public static void main(String[] args) {
Map<String, HashMap<String, Integer>> carOwners = new TreeMap<String, HashMap<String, Integer>>();
HashMap<String, Integer> nameQuantity = new HashMap<String, Integer>();
nameQuantity.put("Audi", 5);
nameQuantity.put("BMW", 4);
carOwners.put("David", sortByValue(nameQuantity));
nameQuantity = new HashMap<String, Integer>();
nameQuantity.put("VW", 10);
nameQuantity.put("MB", 4);
carOwners.put("Izabel", sortByValue(nameQuantity));
for (Map.Entry<String, HashMap<String, Integer>> carOwnerEntry : carOwners.entrySet()) {
System.out.println(carOwnerEntry.getKey());
HashMap<String, Integer> nameQty = carOwnerEntry.getValue();
for (Map.Entry<String, Integer> nameQtyEntry : nameQty.entrySet()) {
System.out.println(nameQtyEntry.getKey() + " " + nameQtyEntry.getValue());
}
}
public static <K, V extends Comparable<? super V>> HashMap<K, V> sortByValue(Map<K, V> map) {
List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());
Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
return (o1.getValue()).compareTo(o2.getValue());
});
HashMap<K, V> result = new LinkedHashMap<K, V>();
for (Map.Entry<K, V> entry : list) {
result.put(entry.getKey(), entry.getValue());
}
return result;
}