How to sort a LinkedHashMap by its value class's field?

落花浮王杯 提交于 2019-12-22 07:36:08

问题


I use the following lines to sort a LinkedHashMap, but not all items are sorted, anything wrong ?

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 Vector<String>();

  public PatternData() { }

  public void add(float data)
  {
    sum+=data;
    totalCount++;
    average=sum/totalCount;
  }

  public void add(float data,String record)
  {
    add(data);
    records.add(record);
  }

  float getAverage() { return average; }

  public int compareTo(patternData o) { return (int)(average-o.average); }
}

回答1:


When you return int, the range when average-o.average is between -1 and 1 will always return 0.

One solution is simply change your compareTo function to:

return Float.compare(average, o.average);



回答2:


You're sorting floating point numbers using integers. Integers don't get rounded; they get truncated. Also, given the way you're actually doing the sorting, consider using a TreeHashMap instead.

(and just to nitpick, Java convention uses lowercase for method and variables names)



来源:https://stackoverflow.com/questions/1117553/how-to-sort-a-linkedhashmap-by-its-value-classs-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!