0

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.

Eklavya
  • 17,618
  • 4
  • 28
  • 57
xyz16179
  • 23
  • 6
  • You [ask about pre-Java 8](https://stackoverflow.com/questions/63243377/get-index-where-the-element-matches-using-lightweight-stream-api-stream/63243498#comment111833634_63243498), but use a method reference (`myObject::getItemDesc`). Are you using Java 8+ or not? – Andy Turner Aug 04 '20 at 09:54
  • @AndyTurner no. – xyz16179 Aug 04 '20 at 09:57
  • how are you using a method reference then? – Andy Turner Aug 04 '20 at 10:00
  • This is a form of "zip" operation (in scala it would be `zipWithIndex`). Java doesn't do it well, but there are some libraries that can help: https://www.baeldung.com/java-collections-zip – Matthew Aug 04 '20 at 15:01

1 Answers1

1

Use IntStream.range:

OptionalInt idx =
    IntStream.range(0, dtaArr.size())
        .filter(i -> dta.get(i).getRateUID().equals(rateUID))
        .findFirst();
Andy Turner
  • 137,514
  • 11
  • 162
  • 243