How to sort arraylist containing objects?

You must be having questions mentioned below:

how to sort arraylist having objects?

How to sort arraylist contianing the objects?

Sorting an arraylist contianing the objects.

Sorting an arraylist of objects.

How to sort a custom made class using ArrayList?

How to use Comparable Interface?

How to sort objects in arraylist using compareTo?

How to sort objects in arraylist in java?

Answer is here : 

By implementing Comparable interface we can achive this:

Comparable interface has compareTo() method which contains the sorting logic for the object.

In the compareTo method we need to write what sorting logic we want to implement.

This compareTo() method is used by sort() method of the collections.

In the example below there is a class  Users and we want to sort the user names alphabetically.


public class Users implements Comparable{ // Users class implementing Comparable Interface

    /** Creates a new instance of Users */

    public String userName;

    public String privilege;

    public Users() {

    }

    public Users(String userName1, String privilege1){

        userName = userName1;

        privilege = privilege1;

    }

    public String toString() {

        return "User ID " + userName + "\n" + "Privilege " + privilege + "\n" ;

    }

    public int compareTo(Object o1) {

        //Sorting logic      

        return ( this.userName.compareTo(((Users) o1).getUserName()) );

    }

    public String getUserName(){

        return userName;

    }

}


Program to test sorting on ArrayList. 


public class Test {

    /** Creates a new instance of Test */

    public Test() {

    }

    public static void main(String[] args) {

        List ts1 = new ArrayList();

        ts1.add(new Users ("Andy","Admin"));

        ts1.add(new Users ("Smith","HR"));

        ts1.add(new Users ("Mark","Non Admin"));

        ts1.add(new Users ("Dwane","Executive"));

        Collections.sort(ts1);

        Iterator itr = ts1.iterator();

        while(itr.hasNext()){

            Object element = itr.next();

            System.out.println(element + "\n");

        }

    }

}
Share on Google Plus

About Pranav

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

2 comments:

  1. Really its useful.. my doubts were cleared..

    ReplyDelete
  2. Perfect. Crisp & Clear.

    ReplyDelete