Generator functions equivalent in Java

Viewed 70481

I would like to implement an Iterator in Java that behaves somewhat like the following generator function in Python:

def iterator(array):
   for x in array:
      if x!= None:
        for y in x:
          if y!= None:
            for z in y:
              if z!= None:
                yield z

x on the java side can be multi-dimensional array or some form of nested collection. I am not sure how this would work. Ideas?

9 Answers

Assuming the Python data structure you describe in your question can be described using the following Java type:

List<List<List<T>>>;

and you want to use it in an operation like this:

for (T z : iterator(array)) {
  // do something with z
}

If so, then one can implement your Python iterator() pretty trivially using Java 8 streams:

public <T> Iterable<T> iterator(List<List<List<T>>> array) {
  return array.stream()
      .filter(Objects::nonNull) // -> emits stream of non-null `x`s
    .flatMap(x -> x.stream()).filter(Objects::nonNull) // -> emits […] `y`s
    .flatMap(y -> y.stream()).filter(Objects::nonNull) // -> emits […] `z`s
    .collect(Collectors.toList()); // get list of non-null `z`s to iterate on
}

Of course, you can not collect the results and output a stream for further streamed processing (people tell me that it is a good idea):

public <T> Stream<T> streamContent(List<List<List<T>>> array) {
  return array.stream()
      .filter(Objects::nonNull) // -> emits stream of non-null `x`s
    .flatMap(x -> x.stream()).filter(Objects::nonNull) // -> emits […] `y`s
    .flatMap(y -> y.stream()).filter(Objects::nonNull); // -> emits […] `z`s
}

// ...

streamContent(array).forEach(z -> {
  // do something with z
});

You can use the iterator of a stream to accomplish this.

// Save the iterator of a stream that generates fib sequence
Iterator<Integer> myGenerator = Stream
        .iterate(new Integer[]{ 1, 1 }, x -> new Integer[] { x[1], x[0] + x[1] })
        .map(x -> x[0]).iterator();

// Print the first 5 elements
for (int i = 0; i < 5; i++) {
    System.out.println(myGenerator.next());
}

System.out.println("done with first iteration");

// Print the next 5 elements
for (int i = 0; i < 5; i++) {
    System.out.println(myGenerator.next());
}

Output:

1
1
2
3
5
done with first iteration
8
13
21
34
55
Related