=doc Make the zipWithIndexExample start with 0 (#31354)

This commit is contained in:
kerr 2022-04-21 19:53:19 +08:00 committed by GitHub
parent bb4ead5b30
commit d4ede3d334
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 16 additions and 14 deletions

View file

@ -24,22 +24,23 @@ public class StatefulMapConcat {
() -> {
// variables we close over with lambdas must be final, so we use a container,
// a 1 element array, for the actual value.
long[] counter = {0};
final long[] index = {0L};
// we return the function that will be invoked for each element
return (element) -> {
counter[0] += 1;
final Pair<String, Long> zipped = new Pair<>(element, index[0]);
index[0] += 1;
// we return an iterable with the single element
return Arrays.asList(new Pair<String, Long>(element, counter[0]));
return Collections.singletonList(zipped);
};
});
letterAndIndex.runForeach(System.out::println, system);
// prints
// Pair(a,1)
// Pair(b,2)
// Pair(c,3)
// Pair(d,4)
// Pair(a,0)
// Pair(b,1)
// Pair(c,2)
// Pair(d,3)
// #zip-with-index
}

View file

@ -15,22 +15,23 @@ class StatefulMapConcat {
def zipWithIndex(): Unit = {
// #zip-with-index
val letterAndIndex = Source("a" :: "b" :: "c" :: "d" :: Nil).statefulMapConcat { () =>
var counter = 0L
var index = 0L
// we return the function that will be invoked for each element
{ element =>
counter += 1
val zipped = (element, index)
index += 1
// we return an iterable with the single element
(element, counter) :: Nil
zipped :: Nil
}
}
letterAndIndex.runForeach(println)
// prints
// (a,1)
// (b,2)
// (c,3)
// (d,4)
// (a,0)
// (b,1)
// (c,2)
// (d,3)
// #zip-with-index
}