Home > OS >  How to filter list with another string list?
How to filter list with another string list?

Time:08-05

Hello I would like to filter list with data only with type which is in anoter arrays.

        myList.filter { itemList->
            typesArray.forEach { itemList.type == it }
            withStatus.forEach { itemList.state.key  == it}
        }

error:

Type mismatch.
Required:
Boolean
Found:
Unit

How to achieve this properly? I have tried also like this:

           myList.any { it ->
           typesArray.contains(it.type)
           withStatus.toTypedArray().contains(it.state.key)
        }

CodePudding user response:

To make things simple: filter should contain a logical expression, result of which is Boolean, more simple - some condition.

myList.filter { /* some condition */ }

Since Boolean result of expression is required, you get the error. That is because the result type of forEach returns Unit, more simple - empty/void value. You can execute a lot of different logic in forEach, however the result of the block itself will be Unit.

I think something like this will work.

myList.filter { item -> 
    typesArray.contains(item.type) && withStatus.contains(item.state.key) 
} 

Note that filter will execute the expression for every item in myList collection.

CodePudding user response:

Part of what you are asking is technically not possible.

First of all, you cannot have a typesArray, because types are not variables and therefore cannot be stored in an array.

Secondly, it makes no sense to filter an array by type, because in Kotlin all variables of an array have to be of the same type.

And regarding the second comparison, you could do it like:

        myList.filter { itemList ->
            typesArray.contains(itemList.state.key)
        }
  • Related