File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sorting of List?

 
Jessica James
Ranch Hand
Posts: 69
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11343
Java Mac Safari
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Have you looked at the sort methods in java.util.Collections? Providing your own Comparator should allow you to sort as desired.
 
Jessica James
Ranch Hand
Posts: 69
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 11343
Java Mac Safari
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's a quick example...
 
Jessica James
Ranch Hand
Posts: 69
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi marc,

Thanks a Lot..

It's working fine..
 
Jessica James
Ranch Hand
Posts: 69
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4864
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic