如何按其值类的字段对LinkedHashMap进行排序? [英] How to sort a LinkedHashMap by its value class's field?

查看:839
本文介绍了如何按其值类的字段对LinkedHashMap进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下几行来对LinkedHashMap进行排序,但并非所有项目都已排序,有什么不对吗?

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); }
}


推荐答案

当你返回int时, average-o.average介于-1和1之间的范围将始终返回0.

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

一个解决方案是将compareTo函数更改为:

One solution is simply change your compareTo function to:

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

这篇关于如何按其值类的字段对LinkedHashMap进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆