2015-12-20 12 views
6

如何排序hashmap由整數值,另一個,我發現答案是here排序一個HashMap的整數值遞減

是寫葉夫根尼·Dorofeev,他的回答是這樣的

HashMap<String, Integer> map = new HashMap<String, Integer>(); 
    map.put("a", 4); 
    map.put("c", 6); 
    map.put("b", 2); 
    Object[] a = map.entrySet().toArray(); 
    Arrays.sort(a, new Comparator() { 
     public int compare(Object o1, Object o2) { 
      return ((Map.Entry<String, Integer>) o2).getValue().compareTo(
        ((Map.Entry<String, Integer>) o1).getValue()); 
     } 
    }); 
    for (Object e : a) { 
     System.out.println(((Map.Entry<String, Integer>) e).getKey() + " : " 
       + ((Map.Entry<String, Integer>) e).getValue()); 
    } 

輸出

c : 6 
a : 4 
b : 2 

我的問題是如何成爲加侖 ??如果我想排序HashMapAsc我該怎麼做?

最後一個問題是:如何排序後的第一個元素?

+2

你也許可以通過在'compare'方法切換'o2'用'o1'顛倒順序 - 獲得的第一個元素就是'a [0]'然後使用與for循環相同的邏輯來獲得值和密鑰!? – luk2302

+0

thanx @ luk2302 :) –

+1

可能的重複[如何對Java中的值排序映射?](http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on java中的值) –

回答

6

用於逆序開關o2o1。用於獲取所述第一元件只在索引0訪問陣列:

Map<String, Integer> map = new HashMap<>(); 
map.put("a", 4); 
map.put("c", 6); 
map.put("b", 2); 
Object[] a = map.entrySet().toArray(); 
Arrays.sort(a, new Comparator() { 
    public int compare(Object o1, Object o2) { 
     return ((Map.Entry<String, Integer>) o1).getValue().compareTo(
       ((Map.Entry<String, Integer>) o2).getValue()); 
    } 
}); 
for (Object e : a) { 
    System.out.println(((Map.Entry<String, Integer>) e).getKey() + " : " 
        + ((Map.Entry<String, Integer>) e).getValue()); 
}   

System.out.println("first element is " + ((Map.Entry<String, Integer>) a[0]).getKey() + " : " 
     + ((Map.Entry<String, Integer>) a[0]).getValue());   

哪個打印

B:2-
一個:4
C:6
第一個元素是B:2-

如果您有權訪問lambda表達式,則可以使用以下方法簡化排序:

Arrays.sort(a, (o1, o2) -> 
    ((Map.Entry<String, Integer>) o1).getValue().compareTo(((Map.Entry<String, Integer>) o2).getValue())); 
2

首先,回答你的問題:只是將compare方法的結果改爲將ASC更改爲DESC。

HashMap<String, Integer> map = new HashMap<String, Integer>(); 
map.put("a", 4); 
map.put("c", 6); 
map.put("b", 2); 
Object[] a = map.entrySet().toArray(); 
Arrays.sort(a, new Comparator() { 
    public int compare(Object o1, Object o2) { 
     // just reverse the result of the comparison 
     return -((Map.Entry<String, Integer>) o2).getValue().compareTo(
       ((Map.Entry<String, Integer>) o1).getValue()); 
    } 
}); 
for (Object e : a) { 
    System.out.println(((Map.Entry<String, Integer>) e).getKey() + " : " 
      + ((Map.Entry<String, Integer>) e).getValue()); 
} 

但是如果你需要一個整理Map工作,我建議你使用的是自己處理的排序TreeMap一個實例。

+0

thanx非常多@Orlangure –

3

在Java 8,你可以這樣做:

System.out.println(map.entrySet().stream().sorted((o1, o2) -> { 
     return o2.getValue().compareTo(o1.getValue()); 
    }).findFirst());//would return entry boxed into optional which you can unbox. 
+0

thanx的答案:) –

+0

沒有probs ..其簡潔和易於閱讀。您不必從對象到輸入進行多次轉換,反之亦然。 – SMA

+0

是的,它非常簡化代碼 –