9

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,731
  • 22
  • 33
  • 46
Roland
  • 7,525
  • 13
  • 61
  • 124
  • 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

18

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
  • 117,005
  • 15
  • 201
  • 306
  • 8
    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