# Kotlin program: Sort integer list in descending order with lambda

## Kotlin Lambda: Exercise-6 with Solution

Write a Kotlin program that implements a lambda expression to sort a list of integers in descending order.

Sample Solution:

Kotlin Code:

``````fun main() {
val numbers = listOf(10, 2, 7, 4, 1, 5, 8, 9, 3, 6)

val sortedList = numbers.sortedByDescending { it }

println("Sorted List in Descending Order:")
sortedList.forEach { println(it) }
}
```
```

Sample Output:

```Sorted List in Descending Order:
10
9
8
7
6
5
4
3
2
1
```

Explanation:

In the above exercise -

• We have a list of integers called "numbers". We use the sortedByDescending function on the numbers list and provide a lambda expression { it } as the sorting criteria.
• Inside the lambda expression, we simply return the element itself (it). This lambda expression tells the sortedByDescending function to sort the list in descending order based on the integer values.
• Finally, we print the sorted list in descending order using println and forEach to iterate over each integer in the sorted list and print it on a separate line.

Kotlin Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿