https://kotlinlang.org logo
#announcements
Title
# announcements
a

andrewoma

03/07/2017, 3:59 AM
@groostav It seems an odd thing to do to me, but here’s a way:
Copy code
fun <T> split(values: List<T>, vararg lengths: Int): Sequence<List<T>> {
    val lengthsSeq = lengths.iterator()
    val valuesSeq = values.iterator()
    return generateSequence { if (lengthsSeq.hasNext()) List<T>(lengthsSeq.next()) { valuesSeq.next() } else null }
}

val result = split(listOf("one", "two", "three", "four", "five", "six", "seven", "eight"), 3, 2, 3).associateBy { it.first() }

assertEquals(result, mapOf(
        "one" to listOf("one", "two", "three"),  //row length == 3
        "four" to listOf("four", "five"),        //len == 2
        "six" to listOf("six", "seven", "eight") //len == 3
))
1
g

groostav

03/07/2017, 11:06 AM
andrewoma: I was doing it as a traversal of a tree. A node has children and each child consumes some number of tokens. I have a list of tokens and want to give them to my children as appropriate. Thus i need to split a list like this
the actual map portion of the result is erroneous, I dont need the
associateBy
, I was just fairly certain that
groupBy
was going to be the mechanism to do it. a
List<List<T>>
is sufficient
4 Views