• Post Reply Bookmark Topic Watch Topic
  • New Topic

Sort a collection of beans

 
Dave Bosky
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I currently receive a collection of beans that is returned to my servlet and set into a request attribute for use in my jsp.

I have a variable in my bean called myName.

What I need to do is order the collection alphabetically by 'myName' before inserting the collection into my request attribute.

How should I do this sort? Could someone provide a simple example?

Thanks,
Dave
 
Steven Bell
Ranch Hand
Posts: 1071
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is a Comparitor interface. You implement that interface. Pass that implementation into the sort method of java.util.Collections or if it is an array the sort method of java.util.Arrays
 
Dave Bosky
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the fast response. I don't suppose you have a little example code snippet that would give me a quick-start in the right direction?

Thanks,
Dave
 
Carl Trusiak
Sheriff
Posts: 3341
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This should get you going in the right direction:
http://www.javaranch.com/newsletter/July2002/newsletterjuly2002.jsp#collections
 
Steven Bell
Ranch Hand
Posts: 1071
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if your collection is already a List you would have

Collections.sort(myList, myComparator);

Otherwise you would probabaly do this:

Object[] ob = myCollection.toArray();
Arrays.sort(ob, myComparator);

For the comparator you would have something like this


you would also want to implement the equals method in your comparator
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!