Bạn có thể không sắp xếp được HashMap, nhưng bạn chắc chắn có thể làm điều gì đó cung cấp hiệu ứng tương tự. Tôi đã có thể sắp xếp chuỗi HashMap < của mình, Số nguyên > bằng giá trị giảm dần của Số nguyên bằng cách sử dụng mã tuyệt vời được đăng tại blog Javarevisited. Nguyên tắc tương tự sẽ được áp dụng cho một HashMap < String, String > đối tượng:
/*
* Java method to sort Map in Java by value e.g. HashMap or Hashtable
* throw NullPointerException if Map contains null values
* It also sort values even if they are duplicates
*/
public static <K extends Comparable,V extends Comparable> Map<K,V> sortByValues(Map<K,V> map){
List<Map.Entry<K,V>> entries = new LinkedList<Map.Entry<K,V>>(map.entrySet());
Collections.sort(entries, new Comparator<Map.Entry<K,V>>() {
@Override
public int compare(Entry<K, V> o1, Entry<K, V> o2) {
return o1.getValue().compareTo(o2.getValue());
// to compare alphabetically case insensitive return this instead
// o1.getValue().toString().compareToIgnoreCase(o2.getValue().toString());
}
});
//LinkedHashMap will keep the keys in the order they are inserted
//which is currently sorted on natural ordering
Map<K,V> sortedMap = new LinkedHashMap<K,V>();
for(Map.Entry<K,V> entry: entries){
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
Để gọi phương pháp này, tôi sử dụng:
Map<String, Integer> sorted = sortByValues(myOriginalHashMapObject);
Read more: http://javarevisited.blogspot.com/2012/12/how-to-sort-hashmap-java-by-key-and-value.html#ixzz2akXStsGj
Nguồn
2013-08-01 20:05:55
Nó phụ thuộc những gì các bài tập về nhà " muốn "bạn làm. Vì không có "sử dụng", có lẽ nó muốn bạn hiển thị/xuất khẩu các sinh viên (trong HashMap) theo một thứ tự cụ thể ...dù sao đi nữa, bài tập về nhà thì thay đổi theo cách đó. –
Ngắt của http://stackoverflow.com/questions/1894081/what-is-the-easiest-way-to-sort-maps-according-to-values-in-java, http://stackoverflow.com/questions/2839003/sorting-in-hash-maps-in-java và có lẽ nhiều hơn thế nữa. – BalusC
Đây phải là một trong 10 câu hỏi Java hàng đầu. –