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

后端 未结 22 2622
天命终不由人
天命终不由人 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条回答
  •  悲哀的现实
    2020-11-22 02:13

    There isn't a way to iterate over a Stream whilst having access to the index because a Stream is unlike any Collection. A Stream is merely a pipeline for carrying data from one place to another, as stated in the documentation:

    No storage. A stream is not a data structure that stores elements; instead, they carry values from a source (which could be a data structure, a generator, an IO channel, etc) through a pipeline of computational operations.

    Of course, as you appear to be hinting at in your question, you could always convert your Stream to a Collection, such as a List, in which you will have access to the indexes.

提交回复
热议问题