This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Sorting Maps 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 » Beginning Java
Bookmark "Sorting Maps" Watch "Sorting Maps" New topic
Author

Sorting Maps

Shasi Sekar
Greenhorn

Joined: Aug 22, 2008
Posts: 23
Hi All,

I have a doubt on sorting a map

i explain the steps i followed.

1. put the keys and values in different collections
2.sort the values
3.iterate through sorted values,then iterate through the key set.
4.get the value from the unsorted map w.r.t to the key iteration
5.compare the value with the iterated value.
6.put the key and value into a sorted map if the comparison succeeds.

when i print the key an value after the successful comparison, i get the out put as required,i.e the output is sorted w.r.t. values.
but when the same output is inserted into a sorted map. I get the output as sorted w.r.t. keys.


what am i missing here.Is there a map which give the output in first in first out pattern


I code is below

Regards,
Shasi Sekar
Shasi Sekar
Greenhorn

Joined: Aug 22, 2008
Posts: 23
i got it ... need to use linked hash map.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37950
    
  22
A linked hash map isn’t sorted; it is ordered. Sorted means you keep the keys from smallest to largest. A linked hash map keeps them from first inserted to last inserted. If you really want sorting, look for a Sorted Map and that link will give hints about which classes you can use.
Shasi Sekar
Greenhorn

Joined: Aug 22, 2008
Posts: 23
yes Ritchie, you are right.But i had sorted the values already using comparator and wanted a map with FIFO.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37950
    
  22
Maps don’t implement FIFO; lists do. But your linked hash map is a combination of a map and a list, so the list bit can implement FIFO for you.
Shasi Sekar
Greenhorn

Joined: Aug 22, 2008
Posts: 23
yes you are very right.That's what i have done
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37950
    
  22
Shasi Sekar wrote:yes you are very right. . . .
Aww shucks, you’ve embarrassed me!

Well done getting it sorted out
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Sorting Maps
 
Similar Threads
HashMap and its cousins
Problem in Creating HashMap object then display in sorted and unsorted order
Hashtable
EL expression question. Getting a value from a map that use Integer like key
Bubble Sort Set using Comparator