Skip to content

Python like Generators in Java

aburkov edited this page Jun 27, 2015 · 1 revision

With xpresso you can define python-like generators in Java.

Python:

def firstn(n):
	num = 0
	while num < n:
		yield num
		num += 1

for i in firstn(500000):
	print i

xpresso:

public Generator<Integer> firstn (final int n) {
	return new Generator<Integer>() {
		public void generate() {
			int num = 0;
			while (num < n) {
				yield(num);
				num++;
			}
		}
	};
}

for (int i : firstn(500000)) 
	x.print(i);
Clone this wiki locally