Search code examples
javasortingfinalextendsimplements

Sorting a collection of objects in Java where implementing class is final


I'm using a public API provided by a 3rd party and I have a collection of objects that are defined as final.

The object has a method getName() which lets me retrieve the String name of the object.

What I need to do is sort the objects by name and what I tried to do initially was extend the original class to implement Comparable. But that's when I found out it was final and therefore not possible.

Apologies for the terminology here... new to Java and still finding my way. Please could you help by providing me with alternative methods?

Thanks,


Solution

  • You can implement your own Comparator without extending the class, and use it as a parameter for Collections.sort:

    public class MyComparator implements Comparator<MyClass> {
        @Override
        int compate (MyClass a, MyClass b) {
            // null handling removed for clarity's sake
            // add it if you need it
            return a.getName().compareTo(b.getName());
        }
    }
    

    And now just use it:

    List<MyClass> myList = ...;
    Collections.sort (myList, new MyComparator());