• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sorting a List of objects by field

 
Adam Teg
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a list of objects for example Object owner with firstName, lastName etc. Is there a quick way to sort the list by any of the fields example lastName?

Thanks
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes. Write a class that implements java.util.Comparator which compares two of your objects however you like. Then call either java.util.Arrays.sort() (if you have an array) or java.util.Collections.sort() (if you have an actual List) to sort the items, passing an instance of your Comparator class as an argument.
 
Arulanand Dayalan
Ranch Hand
Posts: 128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can try using org.apache.commons.beanutils.BeanComparator.

Collections.sort(alList, new BeanComparator(attribute));
Where,

alList is the list which needs to be sorted.
attribute is the bean field on which the list needs to sorted.

Hope this helps.

Thanks and Regards,
Arul.
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You might want to look at this post. It appears to be asking a similar question.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic