listkotlinif-statementlistof

Kotlin - Partition list into 2 lists


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.


Solution

  • 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)