Is there a concise way to iterate over a stream whilst having access to the index in the stream?
String[] names = {\"Sam\",\"Pamela\", \"Dave\", \"Pascal\",
This question (Stream Way to get index of first element matching boolean) has marked the current question as a duplicate, so I can not answer it there; I am answering it here.
Here is a generic solution to get the matching index that does not require an external library.
If you have a list.
public static int indexOf(List items, Predicate matches) {
return IntStream.range(0, items.size())
.filter(index -> matches.test(items.get(index)))
.findFirst().orElse(-1);
}
And call it like this:
int index = indexOf(myList, item->item.getId()==100);
And if using a collection, try this one.
public static int indexOf(Collection items, Predicate matches) {
int index = -1;
Iterator it = items.iterator();
while (it.hasNext()) {
index++;
if (matches.test(it.next())) {
return index;
}
}
return -1;
}