Home > Net >  Sorting a 2 dimensional array of objects in Kotlin
Sorting a 2 dimensional array of objects in Kotlin

Time:08-09

I have a static 2 dimensional array of objects in a Kotlin project:

class Tables {
    companion object{
        lateinit var finalTable: Array<Array<Any?>?>
    }
}

It is a little clearer in Java:

public class Tables {

    public static Object[][] finalTable;
}

The third element in one row of objects in the table, is a string boxed as an object. In other words: finalTable[*][2] is a string describing the item. When I add an item to the array in Kotlin, I want to sort the entire array in alphabetical order of the description.

In Java this is easy:

 Arrays.sort(Tables.finalTable, Comparator.comparing(o -> (String) o[2]));

When I try to use Android Studio to translate the Java code into Kotlin, it produces the following:

Arrays.sort( Tables.finalTable, Comparator.comparing( Function { o: Array<Any?>? -> o[2] as String }) )

This does not work, you have change the String cast as follows:

Arrays.sort( Tables.finalTable, Comparator.comparing( Function { o: Array<Any?>? -> o[2].toString() }) )

This version will compile and run, but it totally messes up the sorting of the table, so it does not work. I have tried variations on this theme, without any success. To get my project to work, I had to create a Java class in the Kotlin project with the functional Java code listed above:

public class ArraySort {
    public void sortArray(){
        Arrays.sort(Tables.finalTable, Comparator.comparing(o -> (String) o[2]));
    }
}

This sorts the table like a charm, but I would prefer to keep my project "pure Kotlin". Can anyone suggest a pure Kotlin method to sort such an array? Thanks!

CodePudding user response:

Unless I'm missing something, you can just do this:

Tables.finalTable.sortBy { it[2] as String }

which sorts your array in place. sortedBy will produce a new copy of the original if that's what you want instead, and might be why the comment suggestions weren't working for you.

But this whole unstructured array situation isn't ideal, the solution is brittle because it would be easy to put the wrong type in that position for a row, or have a row without enough elements, etc. Creating a data structure (e.g. a data class) would allow you to have named parameters you can refer to (making the whole thing safer and more readable) and give you type checking too

  • Related