I have a basic data model that includes a string value. This model is returned in an Array.
My data:
fun getFruits() : Array<FruitModel>{
return arrayOf(
FruitModel(name: "Apple"),
FruitModel(name: "Tomato"),
FruitModel(name: "Pear"),
FruitModel(name: "Plum"),
FruitModel(name: "Banana"),
FruitModel(name: "Watermelon"),
FruitModel(name: "Strawberry"),
FruitModel(name: "Blueberry"),
FruitModel(name: "Blackberry")
)
}
I need to get the position of a specific item based on the fruit name.
Example: If I specify "Plum", I will get 3. If I specify "Blueberry", I will get 7.
How do I get the position of items in an array based on a string value (in this case, name
)
CodePudding user response:
You can use the indexOfFirst
method of ArrayList
for this
val fruits = getFruits()
val index = fruits.indexOfFirst { it.name == "Plum" }