Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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); }
}
like image 558
Frank Avatar asked Jul 13 '09 02:07

Frank


People also ask

Can LinkedHashMap be sorted?

LinkedHashMap maintains insertion order. Convert LinkedHashMap into TreeMap and after that print keys of TreeMap which are sorted in nature.

How can you sort given HashMap on basis of values?

If we need to sort the HashMap by values, we should create a Comparator. It compares two elements based on the values. After that get the Set of elements from the Map and convert Set into the List. Use the Collections.

Is LinkedHashMap values ordered?

LinkedHashMap is a predefined class in Java that is similar to HashMap, contains key and its respective value, unlike HashMap. In LinkedHashMap insertion order is preserved.


1 Answers

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);
like image 162
CookieOfFortune Avatar answered Oct 01 '22 14:10

CookieOfFortune