'How to find object in list which contains specific value?

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.



Solution 1:[1]

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")
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Muhammad Rio