Home > Software design >  Kotlin - Partition list into 2 lists
Kotlin - Partition list into 2 lists

Time:10-07

I want to split a list into 2 lists. One with all elements except last one. Another list which has the last element.

This works fine if the list size is greater than 1.

    val initialList = listOf("1", "2", "3", "4")
    //val initialList = listOf("1")

    val listOfAllElementsExceptLastElement = initialList
      .dropLast(1)
      .map {
        //do some mapping logic
      }

    val listOfLastElement = initialList
      .takeLast(1)
      .map {
        //do some mapping logic
      }

But if the list size is 1 then I want that to be populated in the first list and not the second one. Is it possible to do this without using if condition?

If I use if condition then I need to duplicate the code of listOfAllElementsExceptLastElement and I am trying to avoid that.

CodePudding user response:

I would use chunked for this, and add a special case for the size <= 1 case. By using a destructuring declaration, you can assign both lists at the same time, and avoid duplicating logic.

val (head, tail) = if (list.size > 1) {
    list.chunked(list.size - 1)
} else {
    listOf(list, emptyList())
}

CodePudding user response:

You can do it without code duplication by just calculating the number of last elements depending on the size of the initial list:

val lastN = if (initialList.size > 1) 1 else 0
val listOfAllElementsExceptLastElement = initialList.dropLast(lastN)
val listOfLastElement = initialList.takeLast(lastN)
  • Related