Suppose I have the following array:
List<String> list = ["Pepe","Paco","Lucas","Lucia","Stack"]
and I want to know the position that "Lucas" is in, which would be position 2, but I don't want to do it with a for since if it is an array of 1000 elements it is a lot, is there any way to locate it more optimally?
The function
indexOf(String)
returns us the position, in aint
.If there were multiple occurrences of the element, it would return the first one.
If the
String
does not exist, a-1
.Another similar function is
lastIndexOf()
. It would work the same, except that in the case of multiple occurrences, it would return the index of the last match.In your code it would be: