Search code examples
javasortedmap

Java HashMap sorting


Possible Duplicate:
Java Ordered Map

I have list of product object in the HashMap<Integer,Product> I want to do the sorting

   ProductName  ProductCode Qty     Price 
   Pen          100011       10     10.00     product1
   Penci        100012        5      5.00     product2

    HashMap<Integer,Product> productMap = new HashMap<Integer,Product>();

When the user click on the ProductName ,productCode or Price, the object should sort according to the my requirements.

 I added like this.
 productMap .put(1,product1);
 productMap .put(2,product2);

How can i do this.I want to sort using the object.not key

Please help me.

Thanks in advance


Solution

  • If you don't want to frequently access the values based on the key, you shouldn't use HashMap. Just use a List of the values and implement different Comparator<Product>s. Then sort the list with the appropriate comparator.