2017-05-25 304 views
0

我被要求創建一個toArray方法,它應該分別返回一個Iterator或數組,其中的元素按照它們的「add」計數(HashMap中的值)以升序排序訂購。在類型集合通用數據結構上的Collections.sort()不起作用

的方法排序(名單< T>,比較<超級T>?)是:

不過,我收到以下錯誤消息,不知道如何解決它不適用的參數(設置<的Map.Entry < T,整數>>,新的比較<的Map.Entry < T,整數>>(){})

所以好像我要重寫或創建排序方法。有人能幫助我指出正確的方向嗎?

public class OccurenceSet<T> implements Set<T>{ 

    private HashMap<T,Integer> data; 

    public OccurenceSet(){ 
     this.data = new HashMap<T,Integer>(); 
    } 

    @Override 
    public Object[] toArray() { 

     Set<Map.Entry<T,Integer>> dataSet = data.entrySet(); 
     ArrayList<Map.Entry<T,Integer>> dataList = new ArrayList<>(dataSet); 
     Collections.sort(dataSet, new Comparator<Map.Entry<T,Integer>>() { 
       @Override 
       public int compare(Map.Entry<T,Integer> o1, Map.Entry<T, Integer> o2) { 
        return o1.getValue().compareTo(o2.getValue()); 
       } 
      }); 

     return null; 
    } 
} 
+4

Collections.sort sorts列出,而不是集合。常規集沒有訂單。 – Eran

+3

嘗試Collections.sort(dataList ... – user7294900

回答

2

的HashMap並不意味着保持條目排序順序,但如果你有排序基於鍵或值的HashMap,你可以做到這一點在Java中。

  1. 通過調用地圖
  2. 的entrySet的()方法創建一個自定義的比較,以基於價值的條目排序得到的所有條目。
  3. 將條目集轉換爲列表。
  4. 通過使用Collections.sort()方法通過傳遞值比較器對條目列表排序
  5. 通過按排序順序添加條目來創建LinkedHashMap。
2

「在類型集合的方法排序(名單,比較)不 適用於參數(設置>,新的比較>(){})」

你得到這個異常是因爲Collections#sort方法只能接受List<T>不是設置

點擊此處瞭解詳情:Collections#sort Method