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

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

    In addition to protonpack, jOOλ's Seq provides this functionality (and by extension libraries that build on it like cyclops-react, I am the author of this library).

    Seq.seq(Stream.of(names)).zipWithIndex()
                             .filter( namesWithIndex -> namesWithIndex.v1.length() <= namesWithIndex.v2 + 1)
                             .toList();
    

    Seq also supports just Seq.of(names) and will build a JDK Stream under the covers.

    The simple-react equivalent would similarly look like

     LazyFutureStream.of(names)
                     .zipWithIndex()
                     .filter( namesWithIndex -> namesWithIndex.v1.length() <= namesWithIndex.v2 + 1)
                     .toList();
    

    The simple-react version is more tailored for asynchronous / concurrent processing.

提交回复
热议问题