3

I use the below sortwith method to sort my ArrayList, I suppose it will sort the order number from small number to big number. Such as 10,9,8,7,6....0. But the result is not what I expected.Please kindly help to solve this issue.

companyList.add(companyReg)
companyList.sortedWith(compareBy { it.order })

for (obj in companyList) {
    println("order number: "+obj.order)
}

Println result enter image description here

1
  • Can you add little more code? Also, this log is messy. Add only one occurrence of relevant part of the log Commented Jun 11, 2018 at 7:37

2 Answers 2

9

See this example:

fun main(args: Array<String>) {
    val xx = ArrayList<Int>()
    xx.addAll(listOf(8, 3, 1, 4))
    xx.sortedWith(compareBy { it })

    // prints 8, 3, 1, 4
    xx.forEach { println(it) }

    println()

    val sortedXx = xx.sortedWith(compareBy { it })
    // prints sorted collection
    sortedXx.forEach { println(it) }
}

In Kotlin, most collections are immutable. And collection.sortedWith(...) is an extension function which returns a sorted copy of your collection, but in fact you ignore this result.

Of course, you can use other methods modifying collections (like .sort()), or Collections.sort(collection, comparator). This way of sorting doesn't require assigning new collection (because there is no new collection, only current is modified).

Sign up to request clarification or add additional context in comments.

Comments

1

Try this

companyList = companyList.sortedWith(compareBy { it.order })

You can check the document here https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/sorted-with.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.