5

I know how to find the first element of a list by predicate: Find first element by predicate

Is there an easy way to get the index of that element?

pppery
  • 3,550
  • 19
  • 28
  • 41
Roland
  • 7,028
  • 12
  • 58
  • 109
  • This question is NOT a duplicate to https://stackoverflow.com/questions/23696317/java-8-find-first-element-by-predicate. Although answers to that question can be used to construct an answer to this one, there could also be answers which don't require iterating the stream. – Lii Feb 11 '22 at 13:23

1 Answers1

12

If I understood correctly, that's the classic case where you need IntStream; but that would only apply for a List obviously.

IntStream.range(0, yourList.size())
   .filter(i -> yourList.get(i)... your filter condition)
   .collect(Collectors.toList());
Eugene
  • 110,516
  • 12
  • 173
  • 277
  • 4
    If you really only want the first index, use `findFirst()` instead of `collect(...)`. This will only execute the filter until you find the first match. – Malte Hartwig Apr 25 '17 at 12:01