2014-11-15 60 views
0

所以我有一個HashMap<String, Integer>它表示某個單詞在句子中遇到的次數。我想要做的是將所有單詞放在ArrayList<String>中,首先按遇到單詞的次數排序,然後按字母順序打破關係。我會怎麼做呢?我的代碼看起來像這樣:由兩個不同的屬性對ArrayList進行排序

public class MyClass { 
    private HashMap<String, Integer> map; 
    public ArrayList<String> Order() { 
     ArrayList<String> temp = new ArrayList<>(); 
     (...) 
    } 

回答

0

您需要使用自定義比較器。對於比較方法,如果第一個參數應該小於第二個參數,則需要返回負值,如果它們相等,則返回0;如果第一個參數應該大於第二個參數,則返回正值。

注意,這根據整數值降序排序ArrayList中

import java.util.Comparator; 
import java.util.HashMap; 

public class CustomComparator implements Comparator<String> 
{ 
    HashMap<String, Integer> map; 

    public CustomComparator(HashMap<String, Integer> comparisonMap) 
    { 
     map = comparisonMap; 
    } 

    @Override 
    public int compare(String s1, String s2) 
    { 
     int count1 = map.get(s1); 
     int count2 = map.get(s2); 

     if (count1 == count2) 
      return s1.compareTo(s2); 
     return count2 - count1; 
    } 
} 

兩個步驟來創建和排序的ArrayList:

首先,從HashMap中的添加的每個關鍵ArrayList

ArrayList<String> result = new ArrayList<String>(map.size()); 
result.addAll(map.keySet()); 

然後,使用自定義比較器對ArrayList進行排序:

Collections.sort(result, new CustomComparator(map)); 
相關問題