• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Sort a collection of beans

 
Ranch Hand
Posts: 72
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 1071
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Sheriff
Posts: 3341
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
It's just like a fortune cookie, but instead of a cookie, it's pie. And we'll call it ... tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic