Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ArrayList/HashMap - Sorting

 
kri shan
Ranch Hand
Posts: 1463
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
author
Marshal
Pie
Posts: 21117
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Henry
 
kri shan
Ranch Hand
Posts: 1463
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Pie
Posts: 48952
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3076
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic