Home > database >  How to find object in list which contains specific value?
How to find object in list which contains specific value?

Time:05-06

I have a list with objects. Every object has list with String I want to find a object where any value from List is equal to that value.

val opinionsWithPhotos = state.opinionList.value?.filter { it.attachedPhotos != null }
val specificObject = opinionsWithPhotos?.first { it.attachedPhotos?.find { it == "myValue" } }

I don't know how to iterate over list of strings in every single object and find specific item.

CodePudding user response:

i assume that your data to be like this

data class Foo(val photos:List<String>,...)

val listObj = listOf(Foo(listOf("string1", "string2", "string3", ...), ...)

then if you want to find an object where any value from the inner List is equal to your desired value , you could do like this :

// using any
val output1 : Foo? = listObj.find { foo : Foo ->
   foo.photos.any { it == "myValue" }
}

// or using contains
val output2 : Foo? = listObj.find { foo : Foo ->
   foo.photos.contains("myValue")
}
  • Related