Stream Way to get index of first element matching boolean

Solution 1:

Occasionally there is no pythonic zipWithIndex in java. So I came across something like that:

OptionalInt indexOpt = IntStream.range(0, users.size())
     .filter(i -> searchName.equals(users.get(i)))
     .findFirst();

Alternatively you can use zipWithIndex from protonpack library

Note

That solution may be time-consuming if users.get is not constant time operation.

Solution 2:

Try This:

IntStream.range(0, users.size())
    .filter(userInd-> users.get(userInd).getName().equals(username))
    .findFirst()
    .getAsInt();