• 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

Need some help how to sort the bean data

 
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

I need to sort the values from the Bean.

For Eg:

List list;
list = Sample.getList(); // returns list of bean objects.

for (int i= 0; i < list.size(); i++) {
TestBean bean = (TestBean)list.get(i);
name = bean.getDisplayMibName();
}

I need to sort the names from the bean and assign to new list.
New list contains bean objects in sorted order.(alphabetical order).

Thanks in Advance.
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Copy the list containing the Beans by constructing a new ArrayList with the existing one as the constructor argument. Then sort using the Collections.sort() method. You'll need to provide a Comparator object which compares two of your Beans by using the names and the String.compareTo() method.
 
Ranch Hand
Posts: 884
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I suppose your name attribute is of String type, so if you've all the names as a list (ArrayList/Vector), you're in luck, just use Collections.sort() and it would sort it in ascending order by natural order (in this case, your requirements).

However, if you need it in descending order, you'd have to write your own comparator. Also note that the ascending order may not be what same users expect. For e.g., is "AAA" before or after "aaa", it's pretty subjective here.

Now, if you've overriden your POJO's equals & hashCode methods, you'll just need to implement a Comparator class, pass in the list of POJOs together with the comparator to Collections.sort() and get it done.

Not sure which method would be better in performance though.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic