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

Is there findFirst with position in predicate in Kotlin

I need to find first element in a list which fits predicate. But I need to check with it position in predicate.

    list.findXXX { index, item ->
        index > 19 && item.active
    }

Is there such a function?

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

>Solution :

There is no such function yet, but you can easily write one yourself. It is not a lot of effort at all.

public inline fun <T> Iterable<T>.findIndexed(predicate: (Int, T) -> Boolean): T? {
    forEachIndexed { i, e -> if (predicate(i, e)) return e }
    return null
}

Alternatively, in general you can use a filterIndexed to first filter out the indexes that you want to exclude:

list
//  .asSequence() // if you want to be lazy
    .filterIndexed { i, _ -> i > 19 }
    .find { item -> item.active }

In fact, you could just put the entire condition in filterIndexed and use firstOrNull afterwards. It just may not read as nicely as find.

Of course in this specific case you can also just drop the first 20.

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