Pages

Sorting of objects based on their fields | Java

We experience the problem of sorting certain arrays or values quiet often in the world of programming. Well, When it is the inbuilt data types like int or char or even string, there are inbuilt methods that will solve the problem.
int[] c={1,5,3,7,3,9,100,50,40,30,20,10,11,9,12};
        
        //sorting of normal array
        Arrays.sort(c);
        System.out.print(Arrays.toString(c));

Now the problem is that, how do we solve a problem of sorting a list of custom objects like this one.

public class CustomSortingTest{
 
    int value=0;

    public CustomSortingTest() {
     }
    public CustomSortingTest(int a){
    value=a;
    }
}

The solution is pretty simple actually. I remember my effort some years back trying to create a separate utility method and passing the list of this object and writing whole logic there to sort the list and return another one.

Java when sorting a collection, looks for the method "compareTo(T..)" which is the function for an inbuilt interface which most of the inbuilt classes happens to be implementing. When we write a custom class, we normally do not implement this interface, and so while trying to sort the list, java never finds the interface method. Now you could simply implement this interface and override the method and write your custom logic of sorting there. Below is an example of this one.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 
 * @author Rajan Prasad Upadhyay
 *
 */
public class CustomSortingTest implements Comparable<CustomSortingTest> {
 
 int value=0;

    public CustomSortingTest() {
    }
    public CustomSortingTest(int a){
        value=a;
    }
    public static void main(String[] args) {
        List <CustomSortingTest> a=new ArrayList();
        int[] b={1,5,3,7,3,9,100,50,40,30,20,10,11,9,12};
        int[] c={1,5,3,7,3,9,100,50,40,30,20,10,11,9,12};
        
        //sorting of normal array
        Arrays.sort(c);
        System.out.print(Arrays.toString(c));
        
        //sorting a list of objects based on their certain fields
        for(int i=0;i<b.length;i++){
            a.add(new CustomSortingTest(b[i]));
        }
        Collections.sort(a);
        for(int i=0;i<a.size();i++){
            System.out.print(" "+a.get(i).value);
        }
    }

    @Override
    public int compareTo(CustomSortingTest o) {
        if(value<o.value){
            return -1;
        }else if(value==o.value){
            return 0;
        }else{
            return 1;
        }
    }
}
The logic is preety simple. Just determine when to return -1 and when to return 1 or 0.

Best of luck

No comments:

Post a Comment

If you like to say anything (good/bad), Please do not hesitate...