How to sort ArrayList using Comparator?
Solution 1
Use the Collections.sort(List, Comparator) method:
Collections.sort(students, Student.getCompByName());
Also in your code it would be good to use the List
interface when declaring the List
:
List<Student> students = new ArrayList();
You could also tighten up the code by using a Student[]
and passing it to the ArrayList
constructor:
public static void main(String[] args) {
Student[] studentArr = new Student[]{new Student("Mike"),new Student("Hector"), new Student("Reggie"),new Student("zark")};
List<Student> students = new ArrayList<Student>(Arrays.asList(studentArr));
Collections.sort(students, Student.getCompByName());
for(Student student:students){
System.out.println(student.getName());
}
}
Here is a Gist of the full source.
Solution 2
Use Collections.sort()
:
Collections.sort(students, getCompByName());
Note: might be useful to make your comparator a private static final
variable.
Note 2: modifies the list in place; does not create a new list.
Reeggiie
Updated on July 09, 2022Comments
-
Reeggiie almost 2 years
I have a Class Student that Implements a static method
public static Comparator<Student> getCompByName()
that returns a new comparator object for Student that compares 2 Students objects by the attribute 'name'.
I need to now test this by sorting a students ArrayList by 'name' using my function getCompByName().
Here is my Comparator method in my Student class.
public static Comparator<Student> getCompByName() { Comparator comp = new Comparator<Student>(){ @Override public int compare(Student s1, Student s2) { return s1.name.compareTo(s2.name); } }; return comp; }
And Main where I need to test
public static void main(String[] args) { // TODO code application logic here //--------Student Class Test------------------------------------------- ArrayList<Student> students = new ArrayList(); Student s1 = new Student("Mike"); Student s2 = new Student("Hector"); Student s3 = new Student("Reggie"); Student s4 = new Student("zark"); students.add(s1); students.add(s2); students.add(s3); students.add(S4); //Use getCompByName() from Student class to sort students
Can anyone show me how I would use the getCompByName() in my main to actually sort the ArrayList by name? Im new to comparators and having a hard time with their usages. The method returns a comparator, so Im not sure how this will be implemented. I know I need to use getCompByName() to sort, im just not sure how to implement it.
-
Costi Ciudatu about 10 yearsThat's
Collections.sort(*List*, Comparator)
. -
Kevin Bowersox about 10 years@CostiCiudatu Thanks, updated.