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

后端 未结 22 2201
天命终不由人
天命终不由人 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

    Since guava 21, you can use

    Streams.mapWithIndex()
    

    Example (from official doc):

    Streams.mapWithIndex(
        Stream.of("a", "b", "c"),
        (str, index) -> str + ":" + index)
    ) // will return Stream.of("a:0", "b:1", "c:2")
    

提交回复
热议问题