How to chunk a list in specific value? [Kotlin]

312 Views Asked by At

How to chunk a list in specific value?

Ex: split where current value is 5

val x = listOf(1,2,3,4,5,2,3,1,5,4,1,5)

convert x to this:

x => [[1,2,3,4,5],[2,3,1,5],[4,1,5]]
1

There are 1 best solutions below

0
On

Surprisingly, there isn't a method to do this in the standard library.  But it's not hard to write one yourself, e.g.:

/**
 * Splits a collection into sublists, following each occurrence of the given separator.
 */
fun <T> Collection<T>.splitAfter(separator: T): List<List<T>> {
    val result = mutableListOf<MutableList<T>>()
    
    var newSublist = true
    for (item in this) {
        if (newSublist)
            result += mutableListOf<T>()
        result.last() += item
        newSublist = (item == separator)
    }
    
    return result
}

That does as required:

val x = listOf(1, 2, 3, 4, 5, 2, 3, 1, 5, 4, 1, 5)
println(x.splitAfter(5)) // prints [[1, 2, 3, 4, 5], [2, 3, 1, 5], [4, 1, 5]]

It also handles all the corner cases: an empty list, consecutive separators, and zero or more leading and/or trailing separators, e.g.:

val x = listOf(5, 5, 4, 5, 5, 2)
println(x.splitAfter(5)) // prints [[5], [5], [4, 5], [5], [2]]

(It would be a good idea to include unit tests covering all such cases, of course.)