Lets say I have a list of integers: [2, 4, 4, 6, 1, 8, 3, 5, 2, 2, 2], and I want to split this lists into sub lists so each sub list contain values that match the predicate, or if it doesn't then only the value that didn't match, and it should be in the order of the original list.
So for example, if the predicate is "is even" I expect to get the following result:
[[2, 4, 4, 6],[1],[8],[3, 5],[2, 2, 2]]
I have a code that works, but it's pretty ugly in my opinion and I feel like there should be a much nicer way to write it:
private fun <T : Any> toSubLists(values: List<T>, predicate: (T) -> Boolean): List<List<T>> {
val subLists = mutableListOf<List<T>>()
var currentList = mutableListOf<T>()
values.forEach {
if (!predicate(it)) {
if (currentList.isNotEmpty()) {
subLists.add(currentList)
currentList = mutableListOf()
}
subLists.add(listOf(it))
} else {
currentList.add(it)
}
}
if (currentList.isNotEmpty()) {
subLists.add(currentList)
}
return subLists
}