List sorting in Kotlin

Level 3122 keystrokes

sorted() returns a new list in ascending order and sortedDescending() one in descending order. The original list is not changed, and duplicate values (the two 1s) are kept.

Kotlin code

// Unsorted list that contains 1 twice
1val nums = listOf(3, 1, 4, 1, 5, 9)
// sorted() returns a new list in ascending order; nums itself is unchanged
2val asc = nums.sorted()
// sortedDescending() returns a new list in descending order
3val desc = nums.sortedDescending()
4
// Print [1, 1, 3, 4, 5, 9]
5println(asc)
// Print [9, 5, 4, 3, 1, 1]
6println(desc)

Output

[1, 1, 3, 4, 5, 9]
[9, 5, 4, 3, 1, 1]
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Kotlin code and how often they appear.

  • ,× 5
  • (× 5
  • )× 5
  • =× 3
  • .× 2

More Kotlin examples at level 3

← Kotlin typing practice