Laba Diena
Laba Diena

Reputation: 87

How to sort two arrays in the same way?

I want output to be: [3.0, 2.36, 1.1] of keys and in the same way sorted values [three, one, two]

fun main() {
    var l = 0
        var letters = arrayOf("one", "two", "three")
        var digits = arrayOf(2.36, 1.1, 3.0)
        var list = mutableMapOf<Double, String>()
        repeat(3)
        {
            list.put(digits[l], letters[l])
            l++
        }

        println(list.toSortedMap(compareByDescending<Double> { list[it]) })
}

How can I do that? In my attempt code changes to

[1.1, 3.0, 2.36]
[two, three, one]

Upvotes: 2

Views: 284

Answers (1)

mightyWOZ
mightyWOZ

Reputation: 8315

first make sure letters list contain data in correct order, in your question at second position in digits you have 1.1 and in letters you have two, which seems a mistake to me

    var letters = arrayOf("two", "one", "three")
    var digits = arrayOf(2.36, 1.1, 3.0)

    val x = digits.zip(letters).toMap().toSortedMap { o1, o2 -> o2.compareTo(o1)}
    val keys = x.keys.toList()        // [3.0, 2.36, 1.1]
    val values = x.values.toList()    // [three, two, one]

if you have large data set and don't want to waste memory on in-flight data structures (Pairs, List etc) then you can directly build a SortedMap

val x = emptyMap<Double, String>().toSortedMap{ o1, o2 -> o2.compareTo(o1)}
digits.forEachIndexed{index, value ->
   x[value] = letters[index]
}

Upvotes: 1

Related Questions