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:

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

Practice:

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

Practice:

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

Practice:

2. Return sorted List, Array

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

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

II. Kotlin Array sortBy() by Selector function

1. sortBy()

Method signature:

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

Practice:

We can make a descending sorting by sortByDescending():

Practice:

2. Return sorted List, Array

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

III. Kotlin Array sortWith() with Comparator

1. sortWith()

Method signature:

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

Practice:

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

Practice:

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

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:

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



By grokonez | February 3, 2018.

Last updated on September 18, 2018.



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 *

*