This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Java in General and the fly likes sort a map or arraylist according to the value of the object inside Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "sort a map or arraylist according to the value of the object inside" Watch "sort a map or arraylist according to the value of the object inside" New topic
Author

sort a map or arraylist according to the value of the object inside

Imesh Damith
Greenhorn

Joined: Jul 30, 2009
Posts: 12
I have 400 Employee objects in a hashmap. This employee object contains salary detail.
The Employe objects are now in the hashMap. i want to put these objects in to a array list which is sorted to lowest salary object to come first.

how do i sort the arraylist to come lowest salary first.
pete stein
Bartender

Joined: Feb 23, 2007
Posts: 1561
Collections.sort(myArrayList) will work, but first you have to either have your Employee class implement the Comparable<Employee> interface. Either that or use a Comparator object.
Imesh Damith
Greenhorn

Joined: Jul 30, 2009
Posts: 12
how does it know to sort to salary? Employee object contains firstname, lastname, TP etc.
pete stein
Bartender

Joined: Feb 23, 2007
Posts: 1561
Imesh Damith wrote:how does it know to sort to salary? Employee object contains firstname, lastname, TP etc.

If implementing a Comparable interface, then you class will know how to sort because you will place the sorting logic in the compareTo(....) method. Please google for a tutorial on this as I bet if you read one or two of them, it will become all clear.
Charith De Silva
Greenhorn

Joined: Mar 26, 2009
Posts: 18

This would do your job.

BeanComparator beanComparator = new BeanComparator(colomn);
Collections.sort(arraylist,beanComparator);

Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19216

Only if you have the BeanComparator class in your class path. I certainly don't. Where is it from?


SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
Imesh Damith
Greenhorn

Joined: Jul 30, 2009
Posts: 12
Thanks charith, this is really working.
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: sort a map or arraylist according to the value of the object inside
 
Similar Threads
Object HashCode in HashMap
sort HashMap by Key object's value
JavaRanch Rule Round-up Game Query ??
when to use ArrayList and when to use HashMap
array List Program