Hendra Anggrian
Hendra Anggrian

Reputation: 5858

sort List of Object by one of Object's field

I understand that Collections.sort(list) does the work for a list of strings, but what about list of Object? Say I have this object Contact:

public class Contact implements Serializable {

    private SerializableBitmap picture;
    private String name;
    private String location;

    public Contact() {

    }

    public void setPicture(SerializableBitmap picture) {
        this.picture = picture;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setLocation(String location) {
        this.location = location;
    }

    public SerializableBitmap getPicture() {
        return picture;
    }

    public String getName() {
        return name;
    }

    public String getLocation() {
        return location;
    }
}

Then I have an ArrayList of this object. Is it possible to sort the list based on Contact name? I'm trying to populate it with ListView, but it should be in ascending order.

Upvotes: 0

Views: 1246

Answers (2)

Thanos
Thanos

Reputation: 3665

You need to implement a Custom Comparator like the following

public class ContactComparator implements Comparator<Contact> {
    public int compare(Contact contact1, Contact contact2) {
        //In the following line you set the criterion, 
        //which is the name of Contact in my example scenario
        return contact1.getName().compareTo(contact2.getName());
    }
}

Then all you need is to call it like this (anywhere in your code where you need to have your contacts sorted):

Collections.sort(myContacts, new ContactComparator());

myContacts is the list of Contact objects you need to sort (you name it list in your question).

Upvotes: 1

Ya Wang
Ya Wang

Reputation: 1808

If you are populating a List you should populate it with just a string[] then find Contact by name to get the contact object back. Then you can sort the string[] for the listview.

As seen in the comment you need to create a new array of object string anyway. It's totally up to you which way you want to do it.

Upvotes: 0

Related Questions