我是Java的新手,经常发现我需要对Map<Key, Value>值进行排序.
由于值不是唯一的,我发现自己将其转换keySet为a array,并通过数组排序对该数组进行排序,并使用自定义比较器对与键关联的值进行排序.
有没有更简单的方法?
我使用以下行来对LinkedHashMap进行排序,但并非所有项都已排序,有什么不对吗?
LinkedHashMap<String,PatternData> statisticsMap;
// fill in the map ...
LinkedHashMap<String,PatternData> sortedStatisticsMap=new LinkedHashMap<String,PatternData>(); // Sort it by patternData's average
ArrayList<PatternData> statisticsMapValues=new ArrayList<PatternData>(statisticsMap.values());
Collections.sort(statisticsMapValues,Collections.reverseOrder()); // Sorting it (in reverse order)
patternData last_i=null;
for (PatternData i : statisticsMapValues) // Now, for each value
{
if (last_i==i) continue; // Without dublicates
last_i=i;
for (String s : statisticsMap.keySet()) // Get all hash keys
if (statisticsMap.get(s)==i) // Which have this value
{
sortedStatisticsMap.put(s,i);
}
}
class PatternData implements Comparable<PatternData>
{
float sum=0,average;
int totalCount=0;
Vector<String> records=new …Run Code Online (Sandbox Code Playgroud)