wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Sorting of List? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Sorting of List?" Watch "Sorting of List?" New topic
Author

Sorting of List?

Jessica James
Ranch Hand

Joined: Jan 23, 2007
Posts: 69
Hi friends,

In my program I have a list of beans.. For example,
myBean contains 4 elemets like r1,r2,r3 and r4, myList contains list of myBean objects. How can I sort the List based on any one of value(Eg:r1) in the bean object..

please help me out..

Thanks in advance..
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Have you looked at the sort methods in java.util.Collections? Providing your own Comparator should allow you to sort as desired.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Jessica James
Ranch Hand

Joined: Jan 23, 2007
Posts: 69
Hi..

I know that method sort(List l, Comparator c)..

But I dont know how to use it in my case..

Could you please give me some sample code..
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Here's a quick example...
Jessica James
Ranch Hand

Joined: Jan 23, 2007
Posts: 69
Hi marc,

Thanks a Lot..

It's working fine..
Jessica James
Ranch Hand

Joined: Jan 23, 2007
Posts: 69
Hi..

I have one more doubt..
In your example all of the attributes datatype is int..
In my example all of them are String.. But based on their original datatype(which I will get from DataBase) I have to sort them..
How can I do the sorting for different datatypes..

Can you help me..
[ March 12, 2007: Message edited by: Jessica James ]
Merrill Higginson
Ranch Hand

Joined: Feb 15, 2005
Posts: 4864
Luckily, java.lang.String has a compareTo() method that you can use in your compare method. Be careful, though: with Strings you have to allow for the fact that the String may be null.

If you have custom objects you'd like to sort, have them extend the java.lang.Comparable interface. You will then have to provide your own compareTo() method for the object. Incidentally, if you have a List of objects that implement Comparable, you can sort them without specifying a Comparator.


Merrill
Consultant, Sima Solutions
 
Consider Paul's rocket mass heater.
 
subject: Sorting of List?
 
Similar Threads
Cating Object to ComplexType
Problem adding in ArrayList
itrating through an arraylist
Servlet equivalent to <jsp:useBean ../>
[Struts2] dinamic name for textfield