Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make elements first in a list that match a given condition?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

(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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading