, :
public final class Tuple2<A, B> {
private final A $1;
private final B $2;
public Tuple2(A $1, B $2) {
this.$1 = $1;
this.$2 = $2;
}
public A $1() {
return $1;
}
public B $2() {
return $2;
}
}
:
public static <T> Stream<T> streamOf(Iterator<T> iterator) {
return StreamSupport.stream(
Spliterators.spliteratorUnknownSize(
iterator,
Spliterator.ORDERED),
false);
}
public static <T> Stream<Tuple2<T, Long>> withIndex(
Stream<T> stream, int startIndex) {
Iterator<T> it = stream.iterator();
return streamOf(new Iterator<Tuple2<T, Long>>() {
private long index = startIndex;
@Override
public boolean hasNext() {
return it.hasNext();
}
@Override
public Tuple2<T, Long> next() {
return new Tuple2<>(it.next(), index++);
}
});
}
which create a stream of pairs, with one element being the original element of the stream and the other as an index, then you can easily solve your problem as follows:
Stream<String> originalStream = lines.limit(10).map(String::trim);
withIndex(originalStream, 1)
.forEachOrdered(t -> System.out.printf("Line %d: %s%n", t.$2(), t.$1());
NOTE. This only works with sequential threads , which is what happens.
source
share