This week's book giveaway is in the OCAJP 8 forum.
We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line!
See this thread for details.
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

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
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

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?

Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24193

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));

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,
Joanne Neal

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

I agree. Here's the link:
subject: Sorting a List of objects by field
It's not a secret anymore!