Search code examples
javaarraysalgorithmsortingcomparable

Java - Class Data Type - Sorting Problems


Assume that I have implemented a class Edge which has 4 attributes, all of which are of type int: from to quality length.

In my program , I have created an Edge[] array.

I want to Implement 2 Sorting Parameters -

One of them will sort the Edge array in descending order of the qualities,

The other will sort based on increasing order of lengths.

I will be needing these two orderings in distinct parts of my code.

I will be using the library function Arrays.sort() for sorting.

The only way I know of sorting Class Data Type Arrays to implement compareTo() within the class Edge but this only works for one parameter(quality or length but not both).

How can I implement two sorting functions(2 compareTo() functions ?) and decide which one to be called during sorting? In C++ , we can make many compare functions and simply state the function to go through.How to achieve this in Java?

Note: My goal is to sort an array of DataType Edge using Arrays.sort() , and use two different parameters for sorting and DECIDE which one is to be used at which point.


Solution

  • In Java, you can create 2 classes that implements Comparator, defining your compare method, one for each of your sort orders you desire.

    Then you can pass an instance of one of those Comparators to Arrays.sort.

    If you're using Java 8, you can pass a method reference to Comparator.comparing to construct a Comparator based on a getter method.

    Comparator<Edge> lengthAscEdgeComp = Comparator.comparing(Edge::getLength);
    

    To make a descending sort, you can call reversed.

    Comparator<Edge> qualityDescEdgeComp = Comparator.comparing(Edge::getQuality).reversed();