Create a list / arraylist of objects and sort the list (Java)

arraylist, arrays, java, object

Solution

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.

Problem

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

Original source

Related problems