Kotlin program: Sort integer list in descending order with lambda
Write a Kotlin program that implements a lambda expression to sort a list of integers in descending order.
Pre-Knowledge (Before You Start!)
Before solving this exercise, you should be familiar with the following concepts:
- Lambda Expressions: A lambda expression is a short, anonymous function that can be used to perform operations on elements within collections.
- Sorting Lists: The sortedByDescending() function sorts a list based on the criteria defined in the lambda expression, arranging elements from highest to lowest.
- Iteration: The forEach function allows iterating over each element in a collection to perform an action, such as printing each element.
Hints (Try Before Looking at the Solution!)
Here are some hints to help you solve the problem:
- Hint 1: Create a list of integers that you want to sort.
- Hint 2: Use the sortedByDescending() function with a lambda expression to sort the list.
- Hint 3: Inside the lambda, return each element as is to sort by the values themselves.
- Hint 4: Store the sorted list in a variable.
- Hint 5: Use forEach to iterate over the sorted list and print each number on a new line.
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:
Previous: Filter list of strings with lambda expression.
Next: Convert list of strings to uppercase with lambda.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics