Tuesday 21 July 2015

Sorting an ArrayList of Contacts based on name?

http://stackoverflow.com/questions/1814095/sorting-an-arraylist-of-contacts-based-on-name


Ok so I have a been making an addressbook application and have pretty much finished all the key features but I am looking to implement a sort feature in the program.
I want to sort an Arraylist which is of a type called Contact (contactArray) which is a separate class which contains four fields; name, home number, mobile number and address. So I was looking into using the collection sort yet am not sure how i'd implement this.
Is this the right sort I should be using / is it possible to use or should I look into making a custom sort?
shareimprove this question

marked as duplicate by MarkjlordoSam I ampetertGraviton Jan 3 '13 at 3:41

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
   
This assignment sounds so familiar. Mine is due tonight and I'm running late. Agh! –  David May 3 '12 at 3:00

8 Answers

up vote153down voteaccepted
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 let Contact implement Comparable. Assuming that you want to sort by default on name, then do (nullchecks omitted for simplicity):
public class Contact implements Comparable<Contact> {

    private String name;
    private String phone;
    private Address address;

    public int compareTo(Contact other) {
        return name.compareTo(other.name);
    }

    // Add/generate getters/setters and other boilerplate.
}
so that you can just do
List<Contact> contacts = new ArrayList<Contact>();
// Fill it.

Collections.sort(contacts);

If you want to define an external controllable ordering (which overrides the natural ordering), then you need to create a Comparator:
List<Contact> contacts = new ArrayList<Contact>();
// Fill it.

// Now sort by address instead of name (default).
Collections.sort(contacts, new Comparator<Contact>() {
    public int compare(Contact one, Contact other) {
        return one.getAddress().compareTo(other.getAddress());
    }
}); 

You can even define the Comparators in the Contact itself so that you can reuse them instead of recreating them everytime:
public class Contact {

    private String name;
    private String phone;
    private Address address;

    // ...

    public static Comparator<Contact> COMPARE_BY_PHONE = new Comparator<Contact>() {
        public int compare(Contact one, Contact other) {
            return one.phone.compareTo(other.phone);
        }
    };

    public static Comparator<Contact> COMPARE_BY_ADDRESS = new Comparator<Contact>() {
        public int compare(Contact one, Contact other) {
            return one.address.compareTo(other.address);
        }
    };

}
which can be used as follows:
List<Contact> contacts = new ArrayList<Contact>();
// Fill it.

// Sort by address.
Collections.sort(contacts, Contact.COMPARE_BY_ADDRESS);

// Sort later by phone.
Collections.sort(contacts, Contact.COMPARE_BY_PHONE);

And to cream the top off, you could consider to use a generic javabean comparator:
public class BeanComparator implements Comparator<Object> {

    private String getter;

    public BeanComparator(String field) {
        this.getter = "get" + field.substring(0, 1).toUpperCase() + field.substring(1);
    }

    public int compare(Object o1, Object o2) {
        try {
            if (o1 != null && o2 != null) {
                o1 = o1.getClass().getMethod(getter, new Class[0]).invoke(o1, new Object[0]);
                o2 = o2.getClass().getMethod(getter, new Class[0]).invoke(o2, new Object[0]);
            }
        } catch (Exception e) {
            // If this exception occurs, then it is usually a fault of the developer.
            throw new RuntimeException("Cannot compare " + o1 + " with " + o2 + " on " + getter, e);
        }

        return (o1 == null) ? -1 : ((o2 == null) ? 1 : ((Comparable<Object>) o1).compareTo(o2));
    }

}
which you can use as follows:
// Sort on "phone" field of the Contact bean.
Collections.sort(contacts, new BeanComparator("phone"));
(as you see in the code, possibly null fields are already covered to avoid NPE's during sort)
shareimprove this answer
2 
I'd add the possibility of pre-defining several comparators, and then using them by name... –  Stobor Nov 28 '09 at 23:39
1 
In fact, I just did. Easier than trying to explain myself. –  Stobor Nov 28 '09 at 23:55
   
@Stobor: Nice, thanks. –  BalusC Nov 28 '09 at 23:56
1 
Those Comparator definitions should probably also be static and maybe final too... Or something like that.. –  Stobor Nov 29 '09 at 0:04
5 
Excellent examples, thanks a bunch! –  Patrick Feb 15 '10 at 14:00
This page tells you all you need to know about sorting collections, such as ArrayList.
Basically you need to
  • make your Contact class implement the Comparable interface by
    • creating a method public int compareTo(Contact anotherContact) within it.
  • Once you do this, you can just call Collections.sort(myContactList);,
    • where myContactList is ArrayList<Contact> (or any other collection of Contact).
There's another way as well, involving creating a Comparator class, and you can read about that from the linked page as well.
Example:
public class Contact implements Comparable<Contact> {

    ....

    //return -1 for less than, 0 for equals, and 1 for more than
    public compareTo(Contact anotherContact) {
        int result = 0;
        result = getName().compareTo(anotherContact.getName());
        if (result != 0)
        {
            return result;
        }
        result = getNunmber().compareTo(anotherContact.getNumber());
        if (result != 0)
        {
            return result;
        }
        ...
    }
}

No comments:

Post a Comment