Is there a concise way to iterate over a stream with indices in Java 8?

后端 未结 22 2334
天命终不由人
天命终不由人 2020-11-22 01:42

Is there a concise way to iterate over a stream whilst having access to the index in the stream?

String[] names = {\"Sam\",\"Pamela\", \"Dave\", \"Pascal\",          


        
22条回答
  •  -上瘾入骨i
    2020-11-22 01:52

    If you happen to use Vavr(formerly known as Javaslang), you can leverage the dedicated method:

    Stream.of("A", "B", "C")
      .zipWithIndex();
    

    If we print out the content, we will see something interesting:

    Stream((A, 0), ?)
    

    This is because Streams are lazy and we have no clue about next items in the stream.

提交回复
热议问题