Home > database >  Sorting an array based on different properties of objects by overriding compareTo() method
Sorting an array based on different properties of objects by overriding compareTo() method

Time:04-26

I have a list of Student objects, each of them has 3 properties. Color, Size and their names. I want to sort them in ascending order based on their color first, followed by descending order of size and finally, in ascending order of their names. For example, if input is (first line name, second line color and size):

Maria Jose
branco P
Mangojata Mancuda
vermelho P
Cezar Torres Mo
branco P
Baka Lhau
vermelho P
JuJu Mentina
branco M
Amaro Dinha
vermelho P
Adabi Finho
branco G
Severina Rigudinha
branco G
Carlos Chade Losna
vermelho P

I want output to be as:

branco P Cezar Torres Mo
branco P Maria Jose
branco M JuJu Mentina
branco G Adabi Finho
branco G Severina Rigudinha
vermelho P Amaro Dinha
vermelho P Baka Lhau
vermelho P Carlos Chade Losna
vermelho P Mangojata Mancuda

However, after overriding my compareTo() method so that the list is sorted based on what I want, I'm getting output as:

branco P Maria Jose
branco P Cezar Torres Mo
branco M JuJu Mentina
branco G Adabi Finho
branco G Severina Rigudinha
vermelho P Mangojata Mancuda
vermelho P Baka Lhau
vermelho P Amaro Dinha
vermelho P Carlos Chade Losna

As it can be seen, the color and size are sorted correctly however, I'm having trouble with sorting the names. I've tried multiple methods but none works. I can't understand why. Below is my compareTo() method:

public int compareTo(Student student) {
    int value1 = color.compareTo(student.color);
    if (value1 < 0) {
        int value2 = size.compareTo(student.size);
        if (value2 < 0) {
            int value3 = name.compareTo(student.name);
            if (value3 < 0) {
                return value3;
            }
        }
    }
    return value1;
}

Could someone help me out?

CodePudding user response:

You should go on with comparing the other fields only if the preceding ones are equal, meaning your compareTo result is 0, not greater than 0.

You can take a look here.

CodePudding user response:

I am assuming that you want to sort the data based on ascending order of color, if color is equal then you want to sort in descending order of size, if size is also equal, then sort on ascending order of name. Moreover your java class has all these properties as string type.

public int compareTo(Student student) {
    // If color are not equal, sort ascending on color
    if(!this.color.equals(student.color)){
        return this.color.compareTo(student.color);
    }
    // If color are equal, and size is not equal sort descending on size
    if(!this.size.equals(student.size)){
        return student.size.compareTo(this.size);
    }
    // If color and size are equal, sort ascending on name
    return this.name.compareTo(student.name)      
}
  • Related