Given a list and a condition, how do I make all elements that match that condition be the first elements in a list?
For example,
List:
(10, 100, 12, 12, 14, 12, 1002)
Given the condition that the element is 12, the list should now be
(12, 12, 12, 10, 100, 14, 1002)
Is this an expensive function to be done?
I’ve tried using Kotlins built in sorting function, but it does not sort given a specific value.
>Solution :
A list can be split into a Pair of two lists by a given condition:
val list = listOf(10, 100, 12, 12, 14, 12, 1002)
val result = list.partition { it == 12 }.toList().flatten()
println(result) // Output: [12, 12, 12, 10, 100, 14, 1002]
See Filtering collections: Partition