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:

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

Practice ->

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

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

Practice ->

2. Sorted List Returned

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

II. Kotlin List sortBy() with Selector function

1. sortBy()

Method signature:

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

Practice:

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

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

Practice:

2. Sorted List Returned

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

Method signature:

III. Kotlin List sortWith() with Comparator

1. sortWith()

Method signature:

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

Practice:

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

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:

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

By grokonez | February 1, 2019.



Related Posts


Got Something To Say:

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

*