xyz16179
xyz16179

Reputation: 23

Get index where the element matches using lightweight stream API stream

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.

Upvotes: 0

Views: 88

Answers (1)

Andy Turner
Andy Turner

Reputation: 140319

Use IntStream.range:

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

Upvotes: 1

Related Questions