wood burning stoves 2.0*
The moose likes Java in General and the fly likes Sort a HashMap based on a Value object's attribute Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Sort a HashMap based on a Value object Watch "Sort a HashMap based on a Value object New topic
Author

Sort a HashMap based on a Value object's attribute

Arnav Velimala
Ranch Hand

Joined: Jun 04, 2007
Posts: 37
Hi,

Am trying to sort a Map based on a value object's attribute.
The Map has supplierId(String) as Keys and Supplier object as value. The Map has to be sorted on the Supplier object's name.

But the following code doesn't work!!






Can anyone tell me what's wrong in my code?

Thanks,
Arnav
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19651
    
  18

The list is sorted, but then you put it in a "sorted" map. However, HashMap is not sorted, and it will never be sorted. There is currently only one map that is sorted, and that is TreeMap.

The problem is that any comparator for a TreeMap needs a reference to the TreeMap to be able to sort it. However, it needs to provide the comparator to the TreeMap constructor, so you can't put a reference to the TreeMap right away.

The following may work (I haven't tested it):
The TreeMapComparator should be a static nested class in your current class; its definition is not needed outside of it, only the fact that it is a Comparator.


Edit: of course you can use a LinkedHashMap; that keeps the insertion order. It won't stay ordered if you put new items though, but I'm not quite sure my above solution will handle that well.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Sebastian Janisch
Ranch Hand

Joined: Feb 23, 2009
Posts: 1183
I would rather use this form of implementation:




and thats it.

You can also take away the Comparable from the Supplier class and use a Comparator when sorting.


JDBCSupport - An easy to use, light-weight JDBC framework -
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Sort a HashMap based on a Value object's attribute
 
Similar Threads
determine the input type of the value of the function parameter map
Sorting the countries in Alphabetical Order
Sorting a Map By Value
How to sort Map
Sorting values of a Map.