This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Java in General and the fly likes ArrayList/HashMap - Sorting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "ArrayList/HashMap - Sorting" Watch "ArrayList/HashMap - Sorting" New topic

ArrayList/HashMap - Sorting

kri shan
Ranch Hand

Joined: Apr 08, 2004
Posts: 1432
List<HashMap<String, Integer>> I want to store sorted elements in List. Can i use comparator for Hashmap sorting or any other way ?

[HENRY: fixed brackets corruption]
Henry Wong

Joined: Sep 28, 2004
Posts: 20535

Can i use comparator for Hashmap sorting or any other way ?

Not exactly sure what you are asking? Can you elaborate? Possible answers...

1. There is no concept of a sorted list, like TreeMap but for lists, in the core Java API, that I know of. But I believe that there are a bunch of third party implementations available.

2. You can sort a List with the collections class. And yes, it takes a comparator.


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
kri shan
Ranch Hand

Joined: Apr 08, 2004
Posts: 1432
Henry Wong, Basically i would like to sort HashMap based on the Integer value HashMap<String, Integer>> .
can you give the link for third party implementation
Campbell Ritchie

Joined: Oct 13, 2005
Posts: 46419
Write down the contents of a typical Map which you wish to sort.
Write down how you consider one Map to be "greater" or "less" than another Map.
Then you can implement a Comparator which will enable such sorting.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3028
I don't think that will work. A Comparator is used to sort the keys of a SortedMap. It's of no use sorting a value, which seems to be what kri shan wants. Unfortunately, trying to sort a Map this way is pretty much doomed to failure.

Kri, if you want to sort by the Integer values, you're really going to need a second collection, independent of the Map. Like a List<Integer>, or maybe a List<Map.Entry><String, Integer>>. Or a SortedSet<Integer> or SortedSet<Map.Entry><String, Integer>>. Whenever you put something in the Map, you also put it in the List or Set. (You'll have to re-sort the List; a SortedSet will stay sorted.)

Alternately, maybe you could tell us why you want a Map sorted this way. There may well be a different way to approach the problem.
I agree. Here's the link:
subject: ArrayList/HashMap - Sorting
It's not a secret anymore!