3

Possible Duplicate:
Sorting an ArrayList of Contacts based on name?

I have a student object and then I create ArrayList and add student to the list.

ArrayList<Student_Object> studentsList = new ArrayList<>();

Now, I want to sort the list by studentId fleid. How can I do it?

Is there a better solution? Thanks


So I have this method in the Student _Object class

Class is:

class Student_Object implements Comparator<Student_Object>

The method is:

public int compare(Student_Object student1, Student_Object student2){
    String student1TUID = student1.getTUID();        
    String student2TUID = student2.getTUID();

return student1TUID.compareTo(student2TUID);   


}

From where do I run the statment?

Collections.sort(studentsList);

If I run it from my main class I get error in netbeans:

no suitable method found for sort(ArrayList<Student_Object>)
    method Collections.<T#1>sort(List<T#1>,Comparator<? super T#1>) is not applicable
      (cannot instantiate from arguments because actual and formal argument lists differ in length)
    method Collections.<T#2>sort(List<T#2>) is not applicable
      (inferred type does not conform to declared bound(s)
        inferred: Student_Object
        bound(s): Comparable<? super Student_Object>)
  where T#1,T#2 are type-variables:
    T#1 extends Object declared in method <T#1>sort(List<T#1>,Comparator<? super T#1>)
    T#2 extends Comparable<? super T#2> declared in method <T#2>sort(List<T#2>)
----
(Alt-Enter shows hints)

Got it to work. I used Collections.sort(studentsList, new Student_Object());

Thanks everyone

Community
  • 1
  • 1
Mike
  • 1,302
  • 6
  • 23
  • 43
  • Student_Object is redundant, just use Student – Woot4Moo Oct 24 '12 at 19:44
  • @RohitJain in reality it should be combined and a new question of the form "Sort list based on arbitrary field", however those combinations seem to get knocked down. – Woot4Moo Oct 24 '12 at 19:47

2 Answers2

8

One way would be:

Write a comparator and override compare method. Then use Collections.sort() by passing comparator.

Example:

class StudentComparator implements Comparator<Student> {

    public int compare(Student stud1, Student stud2){

        int stu1ID = stud1.getId();       
        int stu2ID = stud2.getId();

        if(stu1ID > stu2ID)
            return 1;
        else if(stu1ID < st21ID )
            return -1;
        else
            return 0;    
    }

}

Another flavor may be:

 class StudentComparator implements Comparator<Student> {

        public int compare(Student stud1, Student stud2){

            int stu1ID = stud1.getId();       
            int stu2ID = stud2.getId();

           return stud1ID-stu2ID;
        }

    }

This tutorial may help you.

kosa
  • 65,990
  • 13
  • 130
  • 167
  • 1
    Better implement a generic Comparator. No typecast needed. And why not just do: - `return stuID1 - stud2ID;`?? – Rohit Jain Oct 24 '12 at 19:47
  • @RohitJain: The tutorial I have added as reference not using generics, I thought that may confuse OP. Thanks for edit. – kosa Oct 24 '12 at 19:51
  • @RohitJain: I guess stud1-stud2 is not guaranteed to return either 1, -1, 0. Sometimes it could be higher vlaue, isn't it? – kosa Oct 24 '12 at 19:52
  • You're welcome. You can also consider returning simply the difference, rather than that if-else block. that will do the job. :) – Rohit Jain Oct 24 '12 at 19:52
  • Yeah but does it matter? `sort` method just care about, positive or negative value, or 0 for equal. – Rohit Jain Oct 24 '12 at 19:53
  • @RohitJain: You are correct, it just cares about negative (or) positive (or) 0. Updated answer. – kosa Oct 24 '12 at 19:55
  • +1 for posting both the flavours. I like more number of flavours :) – Rohit Jain Oct 24 '12 at 19:59
  • @Nambari Thanks, how to I call the sort? **Collection.sort(studentsList, new StudentComparator());** Like this? – Mike Oct 24 '12 at 20:04
  • Yes, with small correction, it should be Collections NOT Collection. make sure 's' – kosa Oct 24 '12 at 20:05
  • I'm getting: **no suitable method found for sort(ArrayList)** – Mike Oct 24 '12 at 20:10
  • @Mike: Please update question with latest code. – kosa Oct 24 '12 at 20:13
  • @Mike: Can you change ArrayList studentsList = new ArrayList<>(); to ArrayList studentsList = new ArrayList(); ? and see – kosa Oct 24 '12 at 20:26
  • @Nambari I got it to works thanks. I used **Collections.sort(studentsList, new Student_Object());** – Mike Oct 24 '12 at 20:29
  • @Mike: Glad it helped you.Enjoy coding. – kosa Oct 24 '12 at 20:31
4

To do sorting you need to implement the Comparable interface. I would also highly recommend implementing equals and hashCode while you are in there. Example:

public class Student implements Comparable  
{  
    private String name;  
    private int id;  
    ...

    public int compareTo(Student otherStudent)  
    {  
       if(this.id < otherStudent.id)  
       {  
          return -1;
       }  
       else if(this.id > otherStudent.id)  
       {  
           return 1;
       }  
        else{
           return 0;  
        }  

    }  
}  
Woot4Moo
  • 23,987
  • 16
  • 94
  • 151