Skip to content
Advertisement

Get index of element that matches a predicate

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?

Advertisement

Answer

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());
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement