Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sorting Maps

 
Shasi Sekar
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i got it ... need to use linked hash map.
 
Campbell Ritchie
Sheriff
Posts: 48917
58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes Ritchie, you are right.But i had sorted the values already using comparator and wanted a map with FIFO.
 
Campbell Ritchie
Sheriff
Posts: 48917
58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
yes you are very right.That's what i have done
 
Campbell Ritchie
Sheriff
Posts: 48917
58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Shasi Sekar wrote:yes you are very right. . . .
Aww shucks, you’ve embarrassed me!

Well done getting it sorted out
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic