最初のマップをTreeMap、2番目のマップを値で並べ替えます。これを参照してくださいpost
以下は問題のコードスニペットです。
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;
}
あなたは 'HashMap'を並べ替えることができない、使用することを検討してください' LinkedHashMap'ではなく –
'の性質によってHashMap'彼らは秩序を持っていません。それらを並べ替えることによってあなたはどういう意味ですか? – Chris
@TuyenNguyen 'LinkedHashMap'は' HashMap'です。そして技術的には 'LinkedHashMap'もソートできません。 – shmosel