Edward Peters Edward Peters - 2 months ago 10
Java Question

Stream Way to get index of first element matching boolean

I have a

. I want to get the index of the (first) user in the stream with a particular username. I don't want to actually require the
to be
to some described
, just to have the same username.

I can think of ugly ways to do this (iterate and count), but it feels like there should be a nice way to do this, probably by using Streams. So far the best I have is:

int index = users.stream()
.map(user -> user.getName())

Which isn't the worst code I've ever written, but it's not great. It's also not that flexible, as it relies on there being a mapping function to a type with a
function that describes the property you're looking for; I'd much rather have something that could work for arbitrary
Function<T, Boolean>

Anyone know how?


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)))

Alternatively you can use zipWithIndex from protonpack library


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