Binil Surendran
Binil Surendran

Reputation: 2564

Android: Arraylist collection sort

In My array list I have name and number, but its not alphabetical. I am using set adapter method for setting all name and number.

I am confused hot to use collection Sort in array list for both name and number

Can any please give me an idea :)

Upvotes: 0

Views: 835

Answers (3)

Devendra Kulkarni
Devendra Kulkarni

Reputation: 149

Implement Comparable interface to your Contact model like

public class Contact implements Comparable<Contact>

override compareTo method

public int compareTo(Fruit Contact ) 

sort by any field you want

finally use

Arrays.sort(Contacts);

it will sort accordingly

please follow this link.

Upvotes: 1

Beena
Beena

Reputation: 2354

isAsc is boolean variable used to check. You want to sort in ascending order or descending order.

arraySquads is my ArrayList of TeamModal type modal class.

 if (isAsc) {
                Collections.sort(arraySquads, new Comparator<TeamModal>() {
                    @Override
                    public int compare(TeamModal emp1, TeamModal emp2) {
                        String playerName1=emp1.getNick_name());
                        String playerName2=emp2.getNick_name());
                        return playerName1.compareToIgnoreCase(
                                playerName2);
                    }
                });
            }
            else
            {
                Collections.sort(arraySquads, new Comparator<TeamModal>(){
                    public int compare(TeamModal emp1, TeamModal emp2) {
                        String playerName1=emp1.getNick_name();
                        String playerName2=emp2.getNick_name();
                        return  playerName2.compareToIgnoreCase(playerName1);
                    }
                });
            }

Upvotes: 0

santoXme
santoXme

Reputation: 802

I think this will help you:

Person p = new Person("Bruce", "Willis");
Person p1  = new Person("Tom", "Hanks");
Person p2 = new Person("Nicolas","Cage");
Person p3 = new Person("John","Travolta");

ArrayList<Person> list = new ArrayList<Person>();
list.add(p);
list.add(p1);
list.add(p2);
list.add(p3);

Collections.sort(list, new Comparator(){

    public int compare(Object o1, Object o2) {
        Person p1 = (Person) o1;
        Person p2 = (Person) o2;
       return p1.getFirstName().compareToIgnoreCase(p2.getFirstName());
    }

});

This will sort the array list in alphabetically. and the list you got is alphabetically arranged

Upvotes: 0

Related Questions