Home > Software engineering >  filter an arraylist dynamically based on a string value- kotlin
filter an arraylist dynamically based on a string value- kotlin

Time:10-27

I want to filter an arraylist indexes and filter a doc based on the docid I provide.

The below code works for 0th index but cant search the whole list and findout the docid

  var results =
this._items?.userItems?.filter { it -> it.requests.get(0).doc == docid }

Kindly suggest the better way of doing It.

Any help is highly appreciated

Thanks

CodePudding user response:

Assuming that you want to keep only the userItems that have any request with the given docid, you can use it.requests.any { request -> request.doc == docid }.

From the documentation (see the overload that takes in a predicate):

Returns true if at least one entry matches the given predicate.

If you want to get all the requests with the given docid instead, you can use: userItems.flatMap { it.requests }.filter { it.doc == docid }

  • Related