Kotlin List Sort: sort(), sortBy(), sortWith()

kotlin-list-sort-sortby-sortwith-feature-image

In the tutorial, Grokonez introduces how to sort a Kotlin List with methods: sort(), sortBy(), sortWith().

I. Kotlin List sort()

1. sort()

Method signature:

public fun > MutableList.sort(): Unit

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

Practice ->

package com.ozenero.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
	*/
}

descending sorting -> we can use sortDescending(). Method signature:

public fun > MutableList.sortDescending(): Unit

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

Practice ->

package com.ozenero.kotlin

fun main(args : Array){
	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 
	*/
}
2. Sorted List Returned

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

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

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

II. Kotlin List sortBy() with Selector function

1. sortBy()

Method signature:

public inline fun > MutableList.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.ozenero.kotlin

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

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

fun main(args : Array){
	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)
	 */
}

descending sorting, use the sort function: sortByDescending() ->

public inline fun > MutableList.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.ozenero.kotlin

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

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

fun main(args : Array){
	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)
 	*/
}
2. Sorted List Returned

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

Method signature:

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

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

III. Kotlin List sortWith() with Comparator

1. sortWith()

Method signature:

public fun  MutableList.sortWith(comparator: Comparator): Unit

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

Practice:

package com.ozenero.kotlin

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

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

fun main(args : Array){
	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{
								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) 
	 */
}

Descending sorting -> we can re-implement comparator as below:

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

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

public fun  Iterable.sortedWith(comparator: Comparator): List

-> Returns a list of all elements sorted according to the specified [comparator].

12 thoughts on “Kotlin List Sort: sort(), sortBy(), sortWith()”

  1. I was curious if you ever considered changing the layout of your blog? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having one or two images. Maybe you could space it out better?

  2. I was wondering if anyone knows what happened to Dimepiece Los Angeles celebrity streetwear brand? I cannot proceed to the checkout on Dimepiecela site. I’ve read in Vogue that they were acquired by a UK-based hedge fund in excess of $50 m. I have just bought the Meditate Yoga Bag from Amazon and absolutely love it xox

  3. Hi! I know this is kinda off topic but I was wondering which blog platform are you using for this site? I’m getting fed up of WordPress because I’ve had problems with hackers and I’m looking at alternatives for another platform. I would be fantastic if you could point me in the direction of a good platform.

  4. I just like the valuable information you supply in your articles. I抣l bookmark your blog and check once more right here regularly. I am quite sure I will learn many new stuff proper right here! Good luck for the following!

  5. Youre so cool! I dont suppose Ive learn anything like this before. So good to seek out any individual with some authentic ideas on this subject. realy thanks for starting this up. this web site is something that’s needed on the net, someone with a bit originality. helpful job for bringing something new to the web!

  6. 385582 46524Having read this I thought it was quite informative. I appreciate you taking the time and effort to put this write-up together. I once again find myself spending approach to a lot time both reading and commenting. But so what, it was nonetheless worth it! 298272

  7. Hmm it looks like your blog ate my first comment (it was extremely long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog. I as well am an aspiring blog writer but I’m still new to everything. Do you have any recommendations for newbie blog writers? I’d certainly appreciate it.

  8. Thanks for this article. I will also like to mention that it can end up being hard while you are in school and just starting out to initiate a long credit history. There are many college students who are only trying to pull through and have a good or beneficial credit history is often a difficult element to have.

Leave a Reply

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