Back to Blog

Kotlin: Put May as the first in the list

Sandy LaneSandy Lane

Video: Kotlin: Put May as the first in the list by Taught by Celeste AI - AI Coding Coach

Watch full page →

Kotlin: Put May as the First in the List

In Kotlin, rearranging a list to prioritize a specific element, such as moving "May" to the front, can be done efficiently using collection operations. This example demonstrates how to reorder a list so that "May" appears first, while preserving the order of the other months.

Code

fun main() {
  val months = listOf("January", "February", "March", "April", "May", "June", "July")

  // Move "May" to the front while keeping the order of other months
  val reordered = months.sortedWith(compareBy { if (it == "May") 0 else 1 })

  println(reordered) // Output: [May, January, February, March, April, June, July]
}

Key Points

  • Use the sortedWith function and a custom comparator to reorder elements conditionally.
  • Assign a lower sort key (0) to "May" to ensure it appears first in the list.
  • The relative order of other elements is preserved by assigning them a higher sort key (1).
  • This approach works well for simple prioritization without modifying the original list structure.