student
student

Reputation: 380

ArrayList sort by length

I want to sort an ArrayList of objects by the length of the vector objects.

double[] s ={1,2,3,4};
double[] s2 ={1,2};
double[] s3 ={1,2,3};

Student[] Facultate ={new Student(s),new Student(s2)};
ArrayList<Student> FacultateList = new ArrayList<Student>(Arrays.asList(Facultate));

I want FacultateList to be ordered like s2,s3,s.

Upvotes: 1

Views: 429

Answers (1)

mk.
mk.

Reputation: 11710

Use Collections.sort with a custom comparator:

Collections.sort(facultateList, new Comparator<Student>() {
    public int compare(Student a, Student b) {
        return a.getLength().compareTo(b.getLength());
    }
});

Alternatively, if this is the default way to sort students, make Student implement Comparable<Student>, implement the appropriate compareTo method in the class itself, and use Collections.sort without the custom comparator.

(Just an aside that will save you confusion later, the convention in Java is that variables start with a lowercase letter, so facultateList, not FacultateList.)

Upvotes: 5

Related Questions