java 如何按值类的字段对 LinkedHashMap 进行排序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1117553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 15:14:17  来源:igfitidea点击:

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

javasortinglinkedhashmap

提问by Frank

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

我使用以下几行对 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 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); }
}

回答by CookieOfFortune

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

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

One solution is simply change your compareTo function to:

一种解决方案是简单地将您的 compareTo 函数更改为:

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

回答by aberrant80

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.

您正在使用整数对浮点数进行排序。整数不会四舍五入;他们被截断了。此外,考虑到您实际进行排序的方式,请考虑改用 TreeHashMap。

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

(只是为了挑剔,Java 约定对方法和变量名称使用小写字母)