Get index where the element matches using lightweight stream API stream

96 Views Asked by At

I have the following stream and I am using this library for streams:

String itemDescValue = Stream.of(dtaArr).filter(e ->
                 e.getRateUID().equals(rateUID))
                .map(myObject::getItemDesc)
                .findFirst()
                .orElse(null);

I would like to run a stream to get the index on when the value matches. I know I can achieve it using a simple for loop:

for(int i=0 ;i < dtaArr.size(); i++)
        {
            if(dtaArr.get(i).getItemDesc().equals(itemDescValue)){
            //do stuff here
        }
}

How would I get the index on when the value matches using the lightweight stream API.

1

There are 1 best solutions below

5
On

Use IntStream.range:

OptionalInt idx =
    IntStream.range(0, dtaArr.size())
        .filter(i -> dta.get(i).getRateUID().equals(rateUID))
        .findFirst();