How to sort a LinkedHashMap by its value class's field?
10,264
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);
Author by
Frank
I've been a Java developer for over 20 years. Recently got a patent for "Interception-resistant Authentication System And Method" : GATE [ Graphic Access Tabular Entry ]. GATE makes user passwords much safer, it helps you to defeat peeking, keylogging, phishing and dictionary attack. Info : https://gatecybertech.com Demo : https://gatecybertech.net GATE has won multiple cyber security awards. If any organization wants to license it, please contact me.
Updated on June 18, 2022Comments
-
Frank almost 2 years
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); } }
-
Frank almost 15 yearsYes, you are concise and to the point, now it works as intended, thanks !
-
C. K. Young almost 15 yearsA TreeHashMap? Isn't that an oxymoron? A map is usually implemented either as a hash table (HashMap), or a red-black tree (TreeMap), not both. :-)