Ryman Holmes
Ryman Holmes

Reputation: 756

How to sort elements in an ArrayList of Strings?

 PhoneBookCollection phoneBook = new PhoneBookCollection();

I have an ArrayList of PhoneBook objects. (The getCollection method returns the list)

ArrayList<PhoneBook> list = phoneBook.getCollection();


I then iterate through my ArrayList and get the PhoneBook at the i'th index and get its corresponding Telephone.

for(int i = 0; i < list.size(); i++ ){

String phone = phoneBook.getPhoneBook(i).getTelephone();

}

What I want to be able to do now is sort the getTelephone objects in ascending order. I know that ArrayLists don't have a sort method so i'm having a bit of trouble doing this.

Upvotes: 0

Views: 333

Answers (4)

catch32
catch32

Reputation: 18572

The best will be use standart way with java.util.Collections

String class has method compareTo() and will be sorted automtically:

Collections.sort(nameOfList)

Upvotes: 0

Christian Tapia
Christian Tapia

Reputation: 34146

You can create a class that implements Comparator:

public class CustomComparator implements Comparator<PhoneBook> { // Replace PhoneBook with the appropriate
    @Override
    public int compare(PhoneBook t1, PhoneBook t2) {
        return t1.getNumber().compareTo(t2.getNumber()); // Here compare the telephone numbers
    }
}

Then do this:

Collections.sort(list, new CustomComparator());

Upvotes: 2

Udi Cohen
Udi Cohen

Reputation: 1289

You can use the java.util.Collections for that.

Upvotes: 0

pulasthi7
pulasthi7

Reputation: 901

You can use the java.util.Collections class to sort the lists. Use Collections.sort().

Upvotes: 0

Related Questions