aspose file tools*
The moose likes Java in General and the fly likes Sorting a List of objects by field Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Sorting a List of objects by field" Watch "Sorting a List of objects by field" New topic
Author

Sorting a List of objects by field

Adam Teg
Ranch Hand

Joined: Feb 09, 2006
Posts: 36
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

Joined: Jul 08, 2003
Posts: 24166
    
  30

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.


[Jess in Action][AskingGoodQuestions]
Arulanand Dayalan
Ranch Hand

Joined: Aug 10, 2005
Posts: 124
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

Joined: Aug 05, 2005
Posts: 3169
    
  10
You might want to look at this post. It appears to be asking a similar question.


Joanne
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Sorting a List of objects by field
 
Similar Threads
Sorting elements of Vectors in multiple ways
collections: why duplicates arent getting eradicated?
How to get sub lists of a list
write a method to remove emp object based on last name from the arraylist?
collection manipulation using DWR