SortedDescending

This sorts the items in descending order. In the same way as the sort function, items have to implement the Comparable interface:

val numbers = listOf(2, 1, 5, 3, 4)
val sortedDesc = numbers.sortedDescending()

Finally, here is how you can chain these functions and modify some data by only applying functions to it. Imagine that we are given a random list of integers and we have to produce a sorted collection of numbers that are squares of even numbers, where the highest number should be less than 1000, and they should be represented as strings. Here's one way to do it:

val result: List<String> = numbers.filter { n -> n % 2 == 0 }
.map { n -> n * n }
.sorted()
.takeWhile { n -> n < 1000 }
.map { n -> n.toString() }

Most of the functions return an Iterable type as a result and the calls can be chained, thus enabling functional style programming.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.133.233