I want to split a list into parts based on a condi...
# announcements
d
I want to split a list into parts based on a condition. Example: Split on even numbers:
Copy code
val input = listOf(4, 1, 1, 3, 2, 5, 2)
val output = input.chunkedBy { it % 2 == 0 } // should be: [[4, 1, 1, 3], [2, 5], [2]]
Is there such a thing in the standard library?
🚫 1
n
d
groupBy
returns a Map though
n
true
but it’s then quite easy to get its values and put it into a list (or an array)
s
.values
or do you absolutely need a
List
?
d
Yes, I need a list. And I also need the order preserved.
groupBy does not help me here at all, it stuffs things into a bag by a condition
I need to split based on a condition.
n
ok then sorry, i don’t know the stdlib well enough to help you there
😞
d
That's okay
n
chunked()
is based on size...
seems like it should work for you
s
I guess
fold
is the closest you can get
d
partition
only checks a boolean condition
r
condition only boolean can be
Copy code
val input = listOf(4, 1, 1, 3, 2, 5, 2)
println(input.partition({ it % 2 == 0 }))
d
That does not do what I want even remotely.
It shoves all even numbers in one list and uneven ones in the other. That is not what I need.
r
but what do you need? in message you wrote "Split on even numbers"
d
See example input->output above...
r
and what is condition in that example?
d
It specifies the element to split on
Every even number should "start a new list"
r
What if the first n elements (n>0) are not true for the condition?
if one simplifies it to (t)rue and (f)alse, then is the output of the form (f*)(tf*)* ?
f
so basically a repeated
takeWhile
d
Correct
What if the first n elements (n>0) are not true for the condition?
Then they would be in their own group. I want behavior "like String.split".
k
condition.invoke(it)
->
condition(it)
d
thats exactly what I wrote for myself 😄
except i used for..in
k
Out of interest, what is the use case?
d
Parsing a terrible XML document. I get a list of text blocks intermitted with <audio> elements. The <audio> elements specify which audio file to use for the following text blocks.
h
@karelpeeters Fixed. But as I said: It's ugly.
d
I want to parse it into groups of audio+list of text