Kotlin Array sort(), sortBy(), sortWith()

kotlin-array-sort-sortby-sortwith-feature-image

In the tutorial, JavaSampleApproach will guide how to sort Kotlin Array by sort(), sortBy() with selector function, and sortWith() with a comparator.

I. Kotlin Array sort()

1. sort()

Method signature:

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

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

Practice:

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

Practice:

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

Practice:

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 
*/

2. Return sorted List, Array

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> 

If you want to return a List after sorting, we can use sorted() method. Method signature:

// 1.
fun <T : Comparable<T>> Array<out T>.sorted(): List<T>

// 2.
fun <T : Comparable<T>> Array<out T>.sortedDescending(): List<T>

II. Kotlin Array sortBy() by Selector function

1. sortBy()

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.javasampleapproach.kotlin.array.sort

data class Product(val name: String, val price: Double /*USD*/)

fun selector(p: Product): Double = p.price

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))
		
	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

Practice:

package com.javasampleapproach.kotlin.array.sort

data class Product(val name: String, val price: Double /*USD*/)

fun selector(p: Product): Double = p.price

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))

	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)
 	*/
}

2. Return sorted List, Array

If we want to return a List after sorting, we can use sortedBy(). 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>

III. Kotlin Array sortWith() with Comparator

1. sortWith()

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.javasampleapproach.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)
*/

2. Return sorted List, Array

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>


By grokonez | February 3, 2018.

Last updated on April 27, 2021.



Related Posts


2 thoughts on “Kotlin Array sort(), sortBy(), sortWith()”

    1. I already bookmarked it! I will share it to my other friends!!! Thank you so much, now I am able to sort my little polynomials now. Thanks again and great help!

      If you want to get the value only on Product class
      use products[0].name

      Thanks thanks!

Got Something To Say:

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

*