Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort array of objects java with different properties

Tags:

java

I have an object array containing two fields per object. I have to write a method that will sort my array by the first field. I already have a method which extracts the first field from each object

I always get an error message when I call my method to sort.

Here is my code:

public static void trier(String[]code, String[]nom, int nbObj) {
    for(int i = 0; i < nbObj-1; i++) {
        int indMin = i;
        for (int j = i+1; j < nbObj; j++)
            if (code[j].compareTo(code[indMin]) < 0)
                indMin = j;
        if (indMin != i) {
            // permutation :
            String tempo = code[i];
            code[i] = code[indMin];
            code[indMin] = tempo;
    
            // permutation :
            String temp = nom[i];
            nom[i] = nom[indMin];
            nom[indMin] = temp;
        }
    }
}

and the call :

Classe.trier(tableau, tableau, nbObj);

I also tried Class.sort(array.getCode(), array.getName(), nbStudent);

But I still have compilation errors

thank you in advance for your help

like image 540
toatyohan Avatar asked Sep 01 '26 00:09

toatyohan


1 Answers

First of all, you don't have to use 2 separate arrays to contain your data. You can put everything in a single array, but better way is to use Java Collections. Perfect choice is ArrayList. However, you still better combine two fields into a single object. You can do it like this:

public class MyObject {
    String code;
    String nom;

    MyObject(String code, String nom) {
        this.code = code;
        this.nom = nom;
    }
}

Now you have a class containing 2 fields. Your aim is to sort a collection of such objects by their second field (nom). You can do this easily since Java 8:

public static void sort1(ArrayList<MyObject> list) {
    list.sort((obj1, obj2) -> obj1.nom.compareTo(obj2.nom));
}

Or

public static void sort2(ArrayList<MyObject> list) {
    list.sort(Comparator.comparing(MyObject::getNom));
} // However for this you need to add method getNom to MyObject

Remember to put your objects in the collection properly. For example:

MyObject a = new MyObject("abc", "abide");
MyObject b = new MyObject("cab", "whatever you want");

ArrayList<MyObject> list = new ArrayList<>();
list.add(a);
list.add(b);
trier(list);
like image 157
Steyrix Avatar answered Sep 02 '26 15:09

Steyrix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!