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

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

    One possible way is to index each element on the flow:

    AtomicInteger index = new AtomicInteger();
    Stream.of(names)
      .map(e->new Object() { String n=e; public i=index.getAndIncrement(); })
      .filter(o->o.n.length()<=o.i) // or do whatever you want with pairs...
      .forEach(o->System.out.println("idx:"+o.i+" nam:"+o.n));
    

    Using an anonymous class along a stream is not well-used while being very useful.

提交回复
热议问题