您需要使用自定義比較器。對於比較方法,如果第一個參數應該小於第二個參數,則需要返回負值,如果它們相等,則返回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));