Java–通過Values來排序Map的代碼
這是一個通過它的值來排序Map的通用方法。
1: /**
2: * Sort a map by values
3: *
4: * @param map Unsorted map
5: * @return Sorted map
6: */
7: public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
8: List<Map.Entry<K, V>> list = new LinkedList<Map.Entry<K, V>>(map.entrySet());
9: Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
10: public int compare(Map.Entry<K, V> o1, Map.Entry<K, V> o2) {
11: return (o1.getValue()).compareTo(o2.getValue());
12: }
13: });
14:
15: Map<K, V> result = new LinkedHashMap<K, V>();
16: for (Map.Entry<K, V> entry : list) {
17: result.put(entry.getKey(), entry.getValue());
18: }
19: return result;
20: }
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!