Bbabis
Bbabis

Reputation: 195

Sort ArrayList<class> in Java

I have this class:

public class Contact {
private  String firstname;
private String lastname;
private List<Integer> phoneNumber;
private Scanner in;
public Contact(){
    phoneNumber = new ArrayList<>();
    firstname = lastname = "";
    in = new Scanner(System.in);
}
public void setFirstName(){
    firstname = in.nextLine();
} 
public  void setLastName(){
    lastname = in.nextLine();
}
public void setPhoneNumber(){
    phoneNumber.add(in.nextInt());
}
public String getFirstName(){
    return firstname;
}
public  String getLastName(){
    return lastname;
}
public  Integer getPhoneNumber(int position){
    return phoneNumber.get(position);
}
}

Now I want to make a class PhoneBook which have my contacts.. I thought to make it with

Arraylist<Contact>

because it won't have a fixed size.. When I want to sort this arraylist by Lastname what would I do?

Upvotes: 0

Views: 4367

Answers (2)

Akber Choudhry
Akber Choudhry

Reputation: 1785

You would have to put in a custom comparator on lastname, either as a separate class or an anonymous class:

OK, I'm editing as I have some spare time and I guess you are learning Java :)

Add these two methods to the Contact class to test:

public void setLastName(String lastname) {
    this.lastname = lastname;
}
@Override
public String toString() {
    return getLastName();
}

Test:

public class Sort {

    static List<Contact> list = new ArrayList<Contact>();
    static Contact one = new Contact(); 
    static Contact two = new Contact(); 
    static Contact three = new Contact(); 
    public static void main(String[] args) {
        one.setLastName("Smith");
        two.setLastName("Monks");
        three.setLastName("Aaron");
        list.add(one); list.add(two); list.add(three);
        System.out.println("Before: " + list);
        Collections.sort(list, new Comparator<Contact>() {
            public int compare(Contact contact, Contact another) {
                return contact.getLastName().compareToIgnoreCase(another.getLastName());
            }
        });
        System.out.println("After: " + list);
    }
}

Your result should be:

Before: [Smith, Monks, Aaron]
After: [Aaron, Monks, Smith]

Upvotes: 2

Tom
Tom

Reputation: 116

Your Contact class needs to implement the Comparable interface... Then you can use Collections.sort(list) to sort the list.

Edit: If you want to have multiple ways of sorting, then you could also make a class that is implementing the Comparator interface. You can create multiple comparators (or make one configurable), then you can pass the comparator as second parameter to Collections.sort

Here is a link explaining the comparator solution: http://www.vogella.com/blog/2009/08/04/collections-sort-java/

Upvotes: 5

Related Questions