File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Sorting list of Bean 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 list of Bean" Watch "Sorting list of Bean" New topic

Sorting list of Bean

Em Aiy
Ranch Hand

Joined: May 11, 2006
Posts: 226
I have a bean class

This class is being retrieved to my by hibernate in form of list. I need to implementing sorting on it. I just read that i need to Comparable interface on it and then i can do the rest.

I have one question

What if i need to sort the List of this bean on different columns i.e at one place may be i need sorting at field1 and at some place may be i need at date and on the other place i'll be looking to sort the list on id.

What could be the best possible way of doing this?

The difference between <b>failure</b> and <b>success</b> is often being <b>right</b> and being <b>exactly right</b>.
Wirianto Djunaidi
Ranch Hand

Joined: Mar 20, 2001
Posts: 210

You use Comparator instead. You create a Comparator for each of your special case and use it with
Em Aiy
Ranch Hand

Joined: May 11, 2006
Posts: 226
For this I'd have to implement the sort method (which is not a problem). but that method can have only one SORTING rule i.e; either sort on field1, or field2 or date.

What i want is something which can help me sort the List on my require field.
Thomas Thevis
Ranch Hand

Joined: Sep 02, 2008
Posts: 87
Originalliy posted by Muhammad Ali:
For this I'd have to implement the sort method.

Actually not. Wirianto Djunaidi is quite right. Have a look at the java.util.Comparator interface. You don't have to implement sort(), but to provide a Comparator which performs a comparison on pairs of your bean objects. For each column to sort, you can provide a different Comparator.


SCJP 5.0, SCJD in progress
Rob Spoor

Joined: Oct 27, 2005
Posts: 20275

"Muhammad Ali",

Please read your private messages regarding an important announcement.

Thank you,


How To Ask Questions How To Answer Questions
steve souza
Ranch Hand

Joined: Jun 26, 2002
Posts: 862
google with these keywords or similar ones and you should find how to do this...

java comparator multiple fields - a fast, free open source performance tuning api.
JavaRanch Performance FAQ
Em Aiy
Ranch Hand

Joined: May 11, 2006
Posts: 226
That really helped. Thanks guys
I agree. Here's the link:
subject: Sorting list of Bean
jQuery in Action, 3rd edition