I am looking to implement a sort feature for my address book application.
I want to sort an ArrayList<Contact> contactArray
. Contact
is a class which contains four fields: name, home number, mobile number and address. I want to sort on name
.
How can I write a custom sort function to do this?
You shoud use the Arrays.sort function. The containing classes should implement Comparable.
This page tells you all you need to know about sorting collections, such as ArrayList.
Basically you need to
Contact
class implement theComparable
interface bypublic int compareTo(Contact anotherContact)
within it.Collections.sort(myContactList);
,myContactList
isArrayList<Contact>
(or any other collection ofContact
).There's another way as well, involving creating a Comparator class, and you can read about that from the linked page as well.
Example:
I did it by the following way. number and name are two arraylist. I have to sort name .If any change happen to name arralist order then the number arraylist also change its order.
Here's a tutorial about ordering objects:
Although I will give some examples, I would recommend to read it anyway.
There are various way to sort an
ArrayList
. If you want to define a natural (default) ordering, then you need to letContact
implementComparable
. Assuming that you want to sort by default onname
, then do (nullchecks omitted for simplicity):so that you can just do
If you want to define an external controllable ordering (which overrides the natural ordering), then you need to create a
Comparator
:You can even define the
Comparator
s in theContact
itself so that you can reuse them instead of recreating them everytime:which can be used as follows:
And to cream the top off, you could consider to use a generic javabean comparator:
which you can use as follows:
(as you see in the code, possibly null fields are already covered to avoid NPE's during sort)
The Collections.sort is a good sort implementation. If you don't have The comparable implemented for Contact, you will need to pass in a Comparator implementation
Of note:
The merge sort is probably better than most search algorithm you can do.
BalusC and bguiz have already given very complete answers on how to use Java's built-in Comparators.
I just want to add that google-collections has an Ordering class which is more "powerful" than the standard Comparators. It might be worth checking out. You can do cool things such as compounding Orderings, reversing them, ordering depending on a function's result for your objects...
Here is a blog post that mentions some of its benefits.