Kotlin Sorting by: sort(), sortBy(), sortWith() with Array, List Examples

Kotlin sorting with sort - sortby- sortwith

In the tutorial, I will introduce how to sort Kotlin Array using sorting functions: sort(), sortBy() with selector function, and sortWith() with a comparator.

Kotlin sort()

Kotlin Array sort() examples

Method signature:


fun <T : Comparable<T>> Array<out T>.sort()

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

Examples:

val simpleArray = arrayOf(1, 4, 2, 20, 3, 40, 23, 12, 51)
 
// fun <T : Comparable<T>> Array<out T>.sort()
simpleArray.sort()
simpleArray.forEach { print("${it} ") }
/*
  -> 1 2 3 4 12 20 23 40 51
*/

For descending sorting, we can use sortDescending(). Method signature:


public fun <T : Comparable<T>> Array<out T>.sortDescending(): Unit

Coding:


val simpleArray = arrayOf(1, 4, 2, 20, 3, 40, 23, 12, 51)
 
simpleArray.sortDescending()
simpleArray.forEach { print("${it} ") }
/*
  -> 51 40 23 20 12 4 3 2 1 
*/

We can sort for a range in the array by using below method signature:


public fun <T> Array<out T>.sort(
        fromIndex: Int = 0, toIndex: Int = size
      ): Unit

Example:

val simpleArray = arrayOf(1, 4, 2, 20, 3, 40, 23, 12, 51)
 
// public fun <T> Array<out T>.sort(fromIndex: Int = 0, toIndex: Int = size): Unit
// -> Sorts a range in the array in-place.
simpleArray.sort(1, 4)
simpleArray.forEach { print("${it} ") }
/*
  1 2 4 20 3 40 23 12 51 
*/

If you want to reture an Array after sorting, we can use sortedArray() method. Method signature:

// 1.
fun <T : Comparable<T>> Array<T>.sortedArray(): Array<T>
 
// 2.
fun <T : Comparable<T>> Array<T>.sortedArrayDescending(): Array<T> 

Kotlin List sort() examples

Method signature:

public fun <T : Comparable<T>> MutableList<T>.sort(): Unit

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

Practice:

package com.loizenai.kotlin
 
fun main(args : Array){
  val simpleList = mutableListOf(1, 4, 2, 20, 3, 40, 23, 12, 51)
 
  simpleList.sort();
  simpleList.forEach { print("${it} ") }
  /*
    -> 1 2 3 4 12 20 23 40 51
  */

}

For descending sorting, we can use sortDescending(). Method signature:

public fun <T : Comparable<T>> MutableList<T>.sortDescending(): Unit

It sorts elements in the list in-place descending according to their natural sort order.

Practice:

package com.loizenai.kotlin
 
fun main(args : Array<String>){
  val simpleList = mutableListOf(1, 4, 2, 20, 3, 40, 23, 12, 51)
 
  simpleList.sortDescending();
  simpleList.forEach { print("${it} ") }
  /*
    -> 51 40 23 20 12 4 3 2 1 
  */
}

If you want to return a List after sorting, we can use sorted() & sortedDescending() methods.

Method signature:

public fun <T : Comparable<T>> Iterable<T>.sorted(): List<T>
-> Returns a list of all elements sorted according to their natural sort order.
 
public fun <T : Comparable<T>> Iterable<T>.sortedDescending(): List<T>
-> Returns a list of all elements sorted descending according to their natural sort order.

Kotlin sortBy()

Kotlin Array sortBy() examples

Method signature:


public inline fun <T, R : Comparable<R>> Array<out T>.sortBy(
          crossinline selector: (T) -> R?
        ): Unit

-> Sorts elements in the array in-place according to natural sort order of the value returned by specified [selector] function.

Practice:

package com.loizenai.kotlin.array.sort
 
data class Product(val name: String, val price: Double /*USD*/)
 
fun selector(p: Product): Double = p.price
 
fun main(args : Array){
  val products = arrayOf(Product("iPhone 8 Plus 64G", 850.00),
              Product("iPhone 8 Plus 256G", 1100.00),
              Product("Apple iPod touch 16GB", 246.00),
              Product("Apple iPod Nano 16GB", 234.75),
              Product("iPad Pro 9.7-inch 32 GB", 474.98),
              Product("iPad Pro 9.7-inch 128G", 574.99),
              Product("Apple 42mm Smart Watch", 284.93))
    
  products.sortBy({selector(it)})
  
  products.forEach { println(it) }
  /*
    Product(name=Apple iPod Nano 16GB, price=234.75)
    Product(name=Apple iPod touch 16GB, price=246.0)
    Product(name=Apple 42mm Smart Watch, price=284.93)
    Product(name=iPad Pro 9.7-inch 32 GB, price=474.98)
    Product(name=iPad Pro 9.7-inch 128G, price=574.99)
    Product(name=iPhone 8 Plus 64G, price=850.0)
    Product(name=iPhone 8 Plus 256G, price=1100.0)
   */
}

We can make a descending sorting by sortByDescending():

public inline fun <T, R : Comparable<R>> Array<out T>.sortByDescending(
                  crossinline selector: (T) -> R?
                ): Unit

If we want to return a List after sorting below method signature:

fun <T, R : Comparable<R>> Array<out T>.sortedBy(
                                    selector: (T) -> R?
    ): List<T>
    
fun <T, R : Comparable<R>> Array<out T>.sortedByDescending(
                  selector: (T) -> R?
    ): List<T>

Kotlin List sortBy() with Selector function examples

Method signature:

public inline fun <T, R : Comparable<R>> MutableList<T>.sortBy(crossinline selector: (T) -> R?): Unit

-> Sorts elements in the list in-place according to natural sort order of the value returned by specified [selector] function.

Practice:

package com.loizenai.kotlin
 
data class Product(val name: String, val price: Double /*USD*/)
 
fun selector(p: Product): Double = p.price
 
fun main(args : Array<String>){
  val products = mutableListOf(Product("iPhone 8 Plus 64G", 850.00),
              Product("iPhone 8 Plus 256G", 1100.00),
              Product("Apple iPod touch 16GB", 246.00),
              Product("Apple iPod Nano 16GB", 234.75),
              Product("iPad Pro 9.7-inch 32 GB", 474.98),
              Product("iPad Pro 9.7-inch 128G", 574.99),
              Product("Apple 42mm Smart Watch", 284.93))
    
  products.sortBy({selector(it)})
  
  products.forEach { println(it) }
  
  /*
    Product(name=Apple iPod Nano 16GB, price=234.75)
    Product(name=Apple iPod touch 16GB, price=246.0)
    Product(name=Apple 42mm Smart Watch, price=284.93)
    Product(name=iPad Pro 9.7-inch 32 GB, price=474.98)
    Product(name=iPad Pro 9.7-inch 128G, price=574.99)
    Product(name=iPhone 8 Plus 64G, price=850.0)
    Product(name=iPhone 8 Plus 256G, price=1100.0)
   */
}

For descending sorting, use the sort function: sortByDescending():

public inline fun <T, R : Comparable<R>> MutableList<T>.sortByDescending(crossinline selector: (T) -> R?): Unit

-> Sorts elements in the list in-place descending according to natural sort order of the value returned by specified [selector] function.

Practice:

package com.loizenai.kotlin
 
data class Product(val name: String, val price: Double /*USD*/)
 
fun selector(p: Product): Double = p.price
 
fun main(args : Array<String>){
  val products = mutableListOf(Product("iPhone 8 Plus 64G", 850.00),
              Product("iPhone 8 Plus 256G", 1100.00),
              Product("Apple iPod touch 16GB", 246.00),
              Product("Apple iPod Nano 16GB", 234.75),
              Product("iPad Pro 9.7-inch 32 GB", 474.98),
              Product("iPad Pro 9.7-inch 128G", 574.99),
              Product("Apple 42mm Smart Watch", 284.93))
    
  products.sortByDescending({selector(it)})
  
  products.forEach { println(it) }
  
  /*
    Product(name=iPhone 8 Plus 256G, price=1100.0)
    Product(name=iPhone 8 Plus 64G, price=850.0)
    Product(name=iPad Pro 9.7-inch 128G, price=574.99)
    Product(name=iPad Pro 9.7-inch 32 GB, price=474.98)
    Product(name=Apple 42mm Smart Watch, price=284.93)
    Product(name=Apple iPod touch 16GB, price=246.0)
    Product(name=Apple iPod Nano 16GB, price=234.75)
   */
}

If we want to return a List after sorting, we can use sortedBy().

Method signature:

public inline fun <T, R : Comparable<R>> Iterable<T>.sortedBy(crossinline selector: (T) -> R?): List<T>
-> Returns a list of all elements sorted according to natural sort order of the value returned by specified [selector] function.
 
public inline fun <T, R : Comparable<R>> Iterable<T>.sortedByDescending(crossinline selector: (T) -> R?): List<T>
-> Returns a list of all elements sorted descending according to natural sort order of the value returned by specified [selector] function.

Kotlin sortWith()

Kotlin Array sortWith() examples

Method signature:

public fun <T> Array<out T>.sortWith(
        comparator: Comparator<in T>
      ): Unit

-> Sorts the array in-place according to the order specified by the given [comparator].

Practice:

package com.loizenai.kotlin.array.sortwith
 
data class Product(val name: String, val price: Double /*USD*/)
 
fun main(args : Array<String>){
  val products = arrayOf(Product("iPhone 8 Plus 64G", 850.00),
              Product("iPhone 8 Plus 256G", 1100.00),
              Product("Apple iPod touch 16GB", 246.00),
              Product("Apple iPod Nano 16GB", 234.75),
              Product("iPad Pro 9.7-inch 32 GB", 474.98),
              Product("iPad Pro 9.7-inch 128G", 574.99),
              Product("Apple 42mm Smart Watch", 284.93))
    
  // public fun <T> Array<out T>.sortWith(comparator: Comparator<in T>): Unit
  // -> Sorts the array in-place according to the order specified by the given [comparator].
  products.sortWith(object: Comparator<Product>{
                override fun compare(p1: Product, p2: Product): Int = when {
                          p1.price > p2.price -> 1
                          p1.price == p2.price -> 0
                          else -> -1
                        }
            })
  
  products.forEach { println(it) }
  /*
    Product(name=Apple iPod Nano 16GB, price=234.75)
    Product(name=Apple iPod touch 16GB, price=246.0)
    Product(name=Apple 42mm Smart Watch, price=284.93)
    Product(name=iPad Pro 9.7-inch 32 GB, price=474.98)
    Product(name=iPad Pro 9.7-inch 128G, price=574.99)
    Product(name=iPhone 8 Plus 64G, price=850.0)
    Product(name=iPhone 8 Plus 256G, price=1100.0)
   */
}

We can sort a range in the array in-place with the given comparator by method signature:

public fun <T> Array<out T>.sortWith(
            comparator: Comparator<in T>, 
            fromIndex: Int = 0, 
            toIndex: Int = size
          ): Unit

Practice:

products.sortWith(object: Comparator<Product>{
              override fun compare(p1: Product, p2: Product): Int = when {
                        p1.price > p2.price -> 1
                        p1.price == p2.price -> 0
                        else -> -1
                      }
          }, 0, 4)
 
products.forEach { println(it) }
/*
  Product(name=Apple iPod Nano 16GB, price=234.75)
  Product(name=Apple iPod touch 16GB, price=246.0)
  Product(name=iPhone 8 Plus 64G, price=850.0)
  Product(name=iPhone 8 Plus 256G, price=1100.0)
  Product(name=iPad Pro 9.7-inch 32 GB, price=474.98)
  Product(name=iPad Pro 9.7-inch 128G, price=574.99)
  Product(name=Apple 42mm Smart Watch, price=284.93)
*/

For descending sorting, we can re-implement comparator as below:

products.sortWith(object: Comparator<Product>{
              override fun compare(p1: Product, p2: Product): Int = when {
                        p1.price < p2.price -> 1
                        p1.price == p2.price -> 0
                        else -> -1
                      }
          })
 
products.forEach { println(it) }
/*
  Product(name=iPhone 8 Plus 256G, price=1100.0)
  Product(name=iPhone 8 Plus 64G, price=850.0)
  Product(name=iPad Pro 9.7-inch 128G, price=574.99)
  Product(name=iPad Pro 9.7-inch 32 GB, price=474.98)
  Product(name=Apple 42mm Smart Watch, price=284.93)
  Product(name=Apple iPod touch 16GB, price=246.0)
  Product(name=Apple iPod Nano 16GB, price=234.75)
*/

If we want to return a List of all elements sorted according to the specified comparator, we can use sortedWith() method:

fun <T> any_array<T>.sortedWith(
            comparator: Comparator<in T>
          ): List<T>

If you want to return an Array with all elements of this array sorted according the specified comparator, we can use sortedArrayWith() method:

fun <T> any_array<T>.sortedArrayWith(
            comparator: Comparator<in T>
          ): Array<out T>

Kotlin List sortWith() examples

Method signature:

public fun <T> MutableList<T>.sortWith(comparator: Comparator<in T>): Unit

-> Sorts elements in the list in-place according to the order specified with [comparator].

Practice:

package com.loizenai.kotlin
 
data class Product(val name: String, val price: Double /*USD*/)
 
fun selector(p: Product): Double = p.price
 
fun main(args : Array<String>){
  val products = mutableListOf(Product("iPhone 8 Plus 64G", 850.00),
              Product("iPhone 8 Plus 256G", 1100.00),
              Product("Apple iPod touch 16GB", 246.00),
              Product("Apple iPod Nano 16GB", 234.75),
              Product("iPad Pro 9.7-inch 32 GB", 474.98),
              Product("iPad Pro 9.7-inch 128G", 574.99),
              Product("Apple 42mm Smart Watch", 284.93))
    
  products.sortWith(object: Comparator<Product>{
                override fun compare(p1: Product, p2: Product): Int = when {
                          p1.price > p2.price -> 1
                          p1.price == p2.price -> 0
                          else -> -1
                        }
            })
  
  products.forEach { println(it) }
  
  /*
    Product(name=Apple iPod Nano 16GB, price=234.75)
    Product(name=Apple iPod touch 16GB, price=246.0)
    Product(name=Apple 42mm Smart Watch, price=284.93)
    Product(name=iPad Pro 9.7-inch 32 GB, price=474.98)
    Product(name=iPad Pro 9.7-inch 128G, price=574.99)
    Product(name=iPhone 8 Plus 64G, price=850.0)
    Product(name=iPhone 8 Plus 256G, price=1100.0) 
   */
}

For descending sorting -> we can re-implement comparator as below:

products.sortWith(object: Comparator<Product>{
              override fun compare(p1: Product, p2: Product): Int = when {
                        p1.price < p2.price -> 1
                        p1.price == p2.price -> 0
                        else -> -1
                      }
          })

If we want to return a List of all elements sorted according to the specified comparator, we can use sortedWith() method:

public fun <T> Iterable<T>.sortedWith(comparator: Comparator<in T>): List<T>

It returns a list of all elements sorted according to the specified [comparator].

Leave a Reply

Your email address will not be published. Required fields are marked *