Sort ArrayList kotlin

The order of elements is an important aspect of certain collection types. For example, two lists of the same elements are not equal if their elements are ordered differently.

In Kotlin, the orders of objects can be defined in several ways.

First, there is natural order. It is defined for inheritors of the Comparable interface. Natural order is used for sorting them when no other order is specified.

Most built-in types are comparable:

  • Numeric types use the traditional numerical order: 1 is greater than 0; -3.4f is greater than -5f, and so on.

  • Char and String use the lexicographical order: b is greater than a; world is greater than hello.

To define a natural order for a user-defined type, make the type an inheritor of Comparable. This requires implementing the compareTo[] function. compareTo[] must take another object of the same type as an argument and return an integer value showing which object is greater:

  • Positive values show that the receiver object is greater.

  • Negative values show that it's less than the argument.

  • Zero shows that the objects are equal.

Below is a class for ordering versions that consist of the major and the minor part.

class Version[val major: Int, val minor: Int]: Comparable { override fun compareTo[other: Version]: Int = when { this.major != other.major -> this.major compareTo other.major // compareTo[] in the infix form this.minor != other.minor -> this.minor compareTo other.minor else -> 0 } } fun main[] { println[Version[1, 2] > Version[1, 3]] println[Version[2, 0] > Version[1, 5]] }

Custom orders let you sort instances of any type in a way you like. Particularly, you can define an order for non-comparable objects or define an order other than natural for a comparable type. To define a custom order for a type, create a Comparator for it. Comparator contains the compare[] function: it takes two instances of a class and returns the integer result of the comparison between them. The result is interpreted in the same way as the result of a compareTo[] as is described above.

fun main[] { //sampleStart val lengthComparator = Comparator { str1: String, str2: String -> str1.length - str2.length } println[listOf["aaa", "bb", "c"].sortedWith[lengthComparator]] //sampleEnd }

Having the lengthComparator, you are able to arrange strings by their length instead of the default lexicographical order.

A shorter way to define a Comparator is the compareBy[] function from the standard library. compareBy[] takes a lambda function that produces a Comparable value from an instance and defines the custom order as the natural order of the produced values.

With compareBy[], the length comparator from the example above looks like this:

fun main[] { //sampleStart println[listOf["aaa", "bb", "c"].sortedWith[compareBy { it.length }]] //sampleEnd }

The Kotlin collections package provides functions for sorting collections in natural, custom, and even random orders. On this page, we'll describe sorting functions that apply to read-only collections. These functions return their result as a new collection containing the elements of the original collection in the requested order. To learn about functions for sorting mutable collections in place, see the List-specific operations.

The basic functions sorted[] and sortedDescending[] return elements of a collection sorted into ascending and descending sequence according to their natural order. These functions apply to collections of Comparable elements.

fun main[] { //sampleStart val numbers = listOf["one", "two", "three", "four"] println["Sorted ascending: ${numbers.sorted[]}"] println["Sorted descending: ${numbers.sortedDescending[]}"] //sampleEnd }

For sorting in custom orders or sorting non-comparable objects, there are the functions sortedBy[] and sortedByDescending[]. They take a selector function that maps collection elements to Comparable values and sort the collection in natural order of that values.

fun main[] { //sampleStart val numbers = listOf["one", "two", "three", "four"] val sortedNumbers = numbers.sortedBy { it.length } println["Sorted by length ascending: $sortedNumbers"] val sortedByLast = numbers.sortedByDescending { it.last[] } println["Sorted by the last letter descending: $sortedByLast"] //sampleEnd }

To define a custom order for the collection sorting, you can provide your own Comparator. To do this, call the sortedWith[] function passing in your Comparator. With this function, sorting strings by their length looks like this:

fun main[] { //sampleStart val numbers = listOf["one", "two", "three", "four"] println["Sorted by length ascending: ${numbers.sortedWith[compareBy { it.length }]}"] //sampleEnd }

You can retrieve the collection in the reversed order using the reversed[] function.

fun main[] { //sampleStart val numbers = listOf["one", "two", "three", "four"] println[numbers.reversed[]] //sampleEnd }

reversed[] returns a new collection with the copies of the elements. So, if you change the original collection later, this won't affect the previously obtained results of reversed[].

Another reversing function - asReversed[]

  • returns a reversed view of the same collection instance, so it may be more lightweight and preferable than reversed[] if the original list is not going to change.

fun main[] { //sampleStart val numbers = listOf["one", "two", "three", "four"] val reversedNumbers = numbers.asReversed[] println[reversedNumbers] //sampleEnd }

If the original list is mutable, all its changes reflect in its reversed views and vice versa.

fun main[] { //sampleStart val numbers = mutableListOf["one", "two", "three", "four"] val reversedNumbers = numbers.asReversed[] println[reversedNumbers] numbers.add["five"] println[reversedNumbers] //sampleEnd }

However, if the mutability of the list is unknown or the source is not a list at all, reversed[] is more preferable since its result is a copy that won't change in the future.

Finally, there is a function that returns a new List containing the collection elements in a random order - shuffled[]. You can call it without arguments or with a Random object.

fun main[] { //sampleStart val numbers = listOf["one", "two", "three", "four"] println[numbers.shuffled[]] //sampleEnd }

Last modified: 05 March 2022

Sorts the array in-place according to the natural order of its elements.

The sort is stable. It means that equal elements preserve their order relative to each other after sorting.

import kotlin.test.* fun main[args: Array] { //sampleStart class Person[val firstName: String, val lastName: String] : Comparable { override fun compareTo[other: Person]: Int = this.lastName.compareTo[other.lastName] override fun toString[]: String = "$firstName $lastName" } val people = arrayOf[ Person["Ragnar", "Lodbrok"], Person["Bjorn", "Ironside"], Person["Sweyn", "Forkbeard"] ] // before sorting println[people.joinToString[]] // Ragnar Lodbrok, Bjorn Ironside, Sweyn Forkbeard people.sort[] // after sorting println[people.joinToString[]] // Sweyn Forkbeard, Bjorn Ironside, Ragnar Lodbrok //sampleEnd }

Sorts a range in the array in-place.

The sort is stable. It means that equal elements preserve their order relative to each other after sorting.

import kotlin.test.* fun main[args: Array] { //sampleStart class Person[val firstName: String, val lastName: String] : Comparable { override fun compareTo[other: Person]: Int = this.lastName.compareTo[other.lastName] override fun toString[]: String = "$firstName $lastName" } val people = arrayOf[ Person["Ragnar", "Lodbrok"], Person["Bjorn", "Ironside"], Person["Sweyn", "Forkbeard"] ] // before sorting println[people.joinToString[]] // Ragnar Lodbrok, Bjorn Ironside, Sweyn Forkbeard people.sort[0, 2] // after sorting println[people.joinToString[]] // Bjorn Ironside, Ragnar Lodbrok, Sweyn Forkbeard //sampleEnd }

Parameters

fromIndex - the start of the range [inclusive] to sort, 0 by default.

toIndex - the end of the range [exclusive] to sort, size of this array by default.

Exceptions

IndexOutOfBoundsException - if fromIndex is less than zero or toIndex is greater than the size of this array.

IllegalArgumentException - if fromIndex is greater than toIndex.

Sorts a range in the array in-place.

import kotlin.test.* fun main[args: Array] { //sampleStart val intArray = intArrayOf[4, 3, 2, 1] // before sorting println[intArray.joinToString[]] // 4, 3, 2, 1 intArray.sort[0, 3] // after sorting println[intArray.joinToString[]] // 2, 3, 4, 1 //sampleEnd }

Parameters

fromIndex - the start of the range [inclusive] to sort, 0 by default.

toIndex - the end of the range [exclusive] to sort, size of this array by default.

Exceptions

IndexOutOfBoundsException - if fromIndex is less than zero or toIndex is greater than the size of this array.

IllegalArgumentException - if fromIndex is greater than toIndex.

@ExperimentalUnsignedTypes fun UIntArray.sort[]
[source]

@ExperimentalUnsignedTypes fun ULongArray.sort[]
[source]

@ExperimentalUnsignedTypes fun UByteArray.sort[]
[source]

@ExperimentalUnsignedTypes fun UShortArray.sort[]
[source]

Sorts the array in-place.

import kotlin.test.* fun main[args: Array] { //sampleStart val intArray = intArrayOf[4, 3, 2, 1] // before sorting println[intArray.joinToString[]] // 4, 3, 2, 1 intArray.sort[] // after sorting println[intArray.joinToString[]] // 1, 2, 3, 4 //sampleEnd }

@ExperimentalUnsignedTypes fun UIntArray.sort[
    fromIndex: Int = 0,
    toIndex: Int = size]
[source]

@ExperimentalUnsignedTypes fun ULongArray.sort[
    fromIndex: Int = 0,
    toIndex: Int = size]
[source]

@ExperimentalUnsignedTypes fun UByteArray.sort[
    fromIndex: Int = 0,
    toIndex: Int = size]
[source]

@ExperimentalUnsignedTypes fun UShortArray.sort[
    fromIndex: Int = 0,
    toIndex: Int = size]
[source]

Sorts a range in the array in-place.

import kotlin.test.* fun main[args: Array] { //sampleStart val intArray = intArrayOf[4, 3, 2, 1] // before sorting println[intArray.joinToString[]] // 4, 3, 2, 1 intArray.sort[0, 3] // after sorting println[intArray.joinToString[]] // 2, 3, 4, 1 //sampleEnd }

Parameters

fromIndex - the start of the range [inclusive] to sort, 0 by default.

toIndex - the end of the range [exclusive] to sort, size of this array by default.

Exceptions

IndexOutOfBoundsException - if fromIndex is less than zero or toIndex is greater than the size of this array.

IllegalArgumentException - if fromIndex is greater than toIndex.

Sorts elements in the list in-place according to their natural sort order.

The sort is stable. It means that equal elements preserve their order relative to each other after sorting.

import kotlin.test.* fun main[args: Array] { //sampleStart val mutableList = mutableListOf[4, 3, 2, 1] // before sorting println[mutableList.joinToString[]] // 4, 3, 2, 1 mutableList.sort[] // after sorting println[mutableList.joinToString[]] // 1, 2, 3, 4 //sampleEnd }

inline fun MutableList.sort[comparison: [T, T] -> Int]
[source]

Deprecated: Use sortWith[Comparator[comparison]] instead.

@DeprecatedSinceKotlin["1.6"] fun Array.sort[
    comparison: [a: T, b: T] -> Int]
[source]

Deprecated: Use sortWith instead

Sorts the array in-place according to the order specified by the given comparison function.

The sort is stable. It means that equal elements preserve their order relative to each other after sorting.

@DeprecatedSinceKotlin["1.6"] inline fun ByteArray.sort[
    noinline comparison: [a: Byte, b: Byte] -> Int]
[source]

Deprecated: Use other sorting functions from the Standard Library

@DeprecatedSinceKotlin["1.6"] inline fun ShortArray.sort[
    noinline comparison: [a: Short, b: Short] -> Int]
[source]

Deprecated: Use other sorting functions from the Standard Library

@DeprecatedSinceKotlin["1.6"] inline fun IntArray.sort[
    noinline comparison: [a: Int, b: Int] -> Int]
[source]

Deprecated: Use other sorting functions from the Standard Library

@DeprecatedSinceKotlin["1.6"] inline fun LongArray.sort[
    noinline comparison: [a: Long, b: Long] -> Int]
[source]

Deprecated: Use other sorting functions from the Standard Library

@DeprecatedSinceKotlin["1.6"] inline fun FloatArray.sort[
    noinline comparison: [a: Float, b: Float] -> Int]
[source]

Deprecated: Use other sorting functions from the Standard Library

@DeprecatedSinceKotlin["1.6"] inline fun DoubleArray.sort[
    noinline comparison: [a: Double, b: Double] -> Int]
[source]

Deprecated: Use other sorting functions from the Standard Library

@DeprecatedSinceKotlin["1.6"] inline fun CharArray.sort[
    noinline comparison: [a: Char, b: Char] -> Int]
[source]

Deprecated: Use other sorting functions from the Standard Library

Sorts the array in-place according to the order specified by the given comparison function.

Video liên quan

Chủ Đề