| 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.
|
 |
 |
|
|
subject: sort a map or arraylist according to the value of the object inside
|
|
|