Home > OS >  Kotlin: How to filter elements from a list lower than the first element?
Kotlin: How to filter elements from a list lower than the first element?

Time:10-29

I have a function chain going and I need to filter items from a Kotlin list that are lower than the first item.

For example, in [3, 5, 2, 7, 1, 0, 9] I want to be left with [3, 5, 7, 9]

I don't see a way to compare by a value in a functional chain since I don't have a saved reference to the list to get its indices.

CodePudding user response:

I don't think there's a way to do this with functional operators, but if you're opposed to pausing the chain to assign to a variable before continuing, you can use run or let to sort of keep the flow going:

list
    //...
    .run { filter { it < first() } }
    //...
  • Related