=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, // variables we close over with lambdas must be final, so we use a container,
// a 1 element array, for the actual value. // 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 // we return the function that will be invoked for each element
return (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 // 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); letterAndIndex.runForeach(System.out::println, system);
// prints // prints
// Pair(a,1) // Pair(a,0)
// Pair(b,2) // Pair(b,1)
// Pair(c,3) // Pair(c,2)
// Pair(d,4) // Pair(d,3)
// #zip-with-index // #zip-with-index
} }

View file

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