2017-02-15 20 views
2

我想通過使用Collections.sort()對地圖元素(基於值)進行排序。問題是我的程序按降序排列元素,而不是按升序排序。我怎樣才能按升序對它進行排序?以下是我的代碼。請問如何根據java中的升序值對地圖元素進行排序?

package hashTableRR; 

import java.util.*; 
import java.util.Map.Entry; 
public class OrderByValue { 

    public static void main(String [] args){ 

    Map<Integer, Integer> map = new HashMap<Integer, Integer>(); 
    map.put(1, 4); 
    map.put(2, 6); 
    map.put(3, 1); 
    map.put(4, 1); 
    map.put(6, 8); 
    map.put(7, 5); 

    Set<Entry<Integer, Integer>> set = map.entrySet(); 
    List<Entry<Integer, Integer>> list = new ArrayList<Entry<Integer, Integer>>(set); 
    Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() 
    { 
     public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2){ 
      return(o2.getValue()).compareTo(o1.getValue()); 
     } 
    } 

      ); 

    System.out.println("Keys\t\tValues"); 
    for(Map.Entry<Integer, Integer> entry:list) 
    { 
     System.out.println(" "+entry.getKey()+"\t\t "+entry.getValue()); 

    }  


    } 
} 
+2

嘗試使用'return(o1.getValue())。compareTo(o2.getValue());'。請注意,比較順序很重要。 – aUserHimself

+0

非常感謝你,它的工作! – Miji05

+2

可能的重複[按值排序圖](http://stackoverflow.com/questions/109383/sort-a-mapkey-value-by-values-java) –

回答

1

該問題可能在您的Comparator#compare實施中。

您正在返回:o2.getValue().compareTo(o1.getValue())

對於升序排列,你應該返回:o1.getValue().compareTo(o2.getValue())

,這將產生一個負值,如果o1 < o20如果他們是平等的,如果o2 > o1正值。

請參閱稍微加密的文檔here


這裏是什麼值的洞察力,你可以期望你的Comparator來執行Integer S IN的Java進行比較時將返回(全DOC here):

值爲0,如果這個整數等於參數Integer;如果此整數在數字上小於參數Integer,則該值小於0;如果此整數在數值上大於參數整數(有符號比較),則值大於0。

+0

非常感謝您的幫助,你們所有人。 – Miji05

+0

@ Miji05不客氣。 – Mena

1

只需使用:

return(o1.getValue()).compareTo(o2.getValue()); 

會明顯相反的順序

3

只要改變你的compare函數變量的順序

return(o1.getValue()).compareTo(o2.getValue()); 
1
Map<Integer, Integer> unsortedMap = new HashMap<>(); 
    Map<Integer, Integer> sortedMap = new LinkedHashMap<>(); 
    unsortedMap.put(1, 4); 
    unsortedMap.put(2, 6); 
    unsortedMap.put(3, 1); 
    unsortedMap.put(4, 1); 
    unsortedMap.put(6, 8); 
    unsortedMap.put(7, 5); 


    unsortedMap.entrySet(). 
      stream(). 
      sorted(Map.Entry.<Integer, Integer>comparingByValue().reversed()). 
      forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue())); 

    System.out.println(sortedMap); 

如果要按照將密鑰插入Map的順序存儲數據,請使用LinkedHashMapHashMap不保證任何順序。

相關問題