Tôi muốn băm của tôi sắp xếp theo thứ tự giảm dần theo các giá trị. Làm thế nào để làm điều đó trong Java?Cách dễ nhất để sắp xếp bản đồ theo giá trị trong Java là gì?
Trả lời
Sử dụng Collections.reverseOrder().
Tôi nghĩ rằng bit khó với câu hỏi là "theo các giá trị", không phải "giảm dần" – Buhb
A HashMap
(và người tiền nhiệm di sản của nó Hashtable
) là do tự nhiên không có thứ tự. Ngay cả khi bạn sắp xếp nó, nó sẽ vẫn không có thứ tự. Nếu bạn muốn duy trì thứ tự chèn, hãy sử dụng LinkedHashMap
để thay thế. Nếu bạn muốn sắp xếp tự động trên các phím , bất kể thứ tự chèn, thì hãy sử dụng SortedMap
để thay thế.
Nếu bạn muốn sắp xếp Map
trên giá trị, thì về cơ bản bạn cần đặt cặp khóa/giá trị vào một loại cấu trúc dữ liệu có thể sắp xếp khác, ví dụ: List<Entry<K, V>>
, sau đó sắp xếp nó bằng cách sử dụng Collections#sort()
với sự trợ giúp của một Compatator<Entry<K, V>>
và cuối cùng repopulate một LinkedHashMap
với nó (không phải là HashMap
hoặc bạn sẽ mất thứ tự một lần nữa).
Dưới đây là một ví dụ cơ bản (để lại rõ ràng ngoại lệ runtime xử lý sang một bên):
// Prepare.
Map<String, String> map = new HashMap<String, String>();
map.put("foo", "bar");
map.put("bar", "waa");
map.put("waa", "foo");
System.out.println(map); // My JVM shows {waa=foo, foo=bar, bar=waa}
// Get entries and sort them.
List<Entry<String, String>> entries = new ArrayList<Entry<String, String>>(map.entrySet());
Collections.sort(entries, new Comparator<Entry<String, String>>() {
public int compare(Entry<String, String> e1, Entry<String, String> e2) {
return e1.getValue().compareTo(e2.getValue());
}
});
// Put entries back in an ordered map.
Map<String, String> orderedMap = new LinkedHashMap<String, String>();
for (Entry<String, String> entry : entries) {
orderedMap.put(entry.getKey(), entry.getValue());
}
System.out.println(orderedMap); // {foo=bar, waa=foo, bar=waa}
Để sắp xếp nó descencing, sử dụng Comparator
sau. Về cơ bản chỉ trao đổi các mục để so sánh:
Collections.sort(entries, new Comparator<Entry<String, String>>() {
public int compare(Entry<String, String> e1, Entry<String, String> e2) {
return e2.getValue().compareTo(e1.getValue()); // Sorts descending.
}
});
Sau đây là cách tôi làm điều đó:
public static <K, V extends Comparable<V>> Map<K, V> sortByValues(final Map<K, V> map) {
Comparator<K> valueComparator = new Comparator<K>() {
public int compare(K k1, K k2) {
int compare = map.get(k2).compareTo(map.get(k1));
if (compare == 0) return 1;
else return compare;
}
};
Map<K, V> sortedByValues = new TreeMap<K, V>(valueComparator);
sortedByValues.putAll(map);
return sortedByValues;
}
bạn có thể cụ thể hơn về vấn đề của bạn? có thể là một thay thế cho sắp xếp theo giá trị, tùy thuộc vào vấn đề thực tế của bạn. – Carl