I just encountered the situation that I needed to know the index (position) of an element inside a list, but only had a predicate expression to identify the element. I had a look for a Stream function like
int index = list.stream().indexOf(e -> "TESTNAME".equals(e.getName()));
but to no avail. Of course, I could write it like this:
int index = list.indexOf(list.stream().filter(e -> "TESTNAME".equals(e.getName()))
.findFirst().get());
But this would a) iterate over the list twice (in the worst case that the element would be the last one) and b) would fail if no element matches the predicate (where I would prefer a -1 index).
I wrote a utility method for this functionality:
public static <T> int indexOf(List<T> list, Predicate<? super T> predicate) {
int idx = 0;
for (Iterator<T> iter = list.iterator(); iter.hasNext(); idx++) {
if (predicate.test(iter.next())) {
return idx;
}
}
return -1;
}
But as this seems to be a really trivial algorithm, I would have expected it somewhere in the Java 8 Stream API. Did I just miss it, or is there really no such function? (Bonus question: In case there is no such method, is there a good reason? Is working with the index in functional programming perhaps an anti-pattern?)