user9634982
user9634982

Reputation: 579

How to implement custom sort on property inside .class file in Java 7

I am required to sort Student objects on the basis of their name. Please note there is no implementation of compareTo() in the Student class, simple getters and setters only and the class itself is part of school.jar which is I am using in my education portal project. How do I access those fields, I can introduce base class for the same but the Student class marked as final.

Is this use case technically feasible or not? If so, how do I achieve it?

Upvotes: 3

Views: 412

Answers (2)

Reto Höhener
Reto Höhener

Reputation: 5808

List<Student> list = new ArrayList<>();
Collections.sort(list, (a, b) -> a.getName().compareToIgnoreCase(b.getName()));

Upvotes: 1

Mureinik
Mureinik

Reputation: 311823

You don't need to modify the Student class - you can introduce your own Comparator:

public class StudentNameComparator implements Comparator<Student> {
    @Override
    int compare(Student s1, Student s2) {
        return s1.getName().compareTo(s2.getName());
    }
}

And then use it:

Collections.sort(listOfStudents, new StudentNameComparator());

EDIT:
Mandatory comment: Java 8 (or later) would allow for some syntactic sugar around this (such as Comparator.comparing(Student::getName)), but the requirement was to use Java 7.

Upvotes: 6

Related Questions