Skip to content

Instantly share code, notes, and snippets.

@andrewrlee
Last active August 29, 2015 14:17
Show Gist options
  • Select an option

  • Save andrewrlee/69b71e8466752bb969b5 to your computer and use it in GitHub Desktop.

Select an option

Save andrewrlee/69b71e8466752bb969b5 to your computer and use it in GitHub Desktop.
Jave 8 streaming with index
	public static <T> Function<T, IndexedItem<T>> indexed() {
		AtomicInteger count = new AtomicInteger();
		return (t) -> new IndexedItem<T>(count.getAndIncrement(), t);
	}

	public static class IndexedItem<T> {
		public final Integer index;
		public final T item;

		public IndexedItem(Integer index, T item) {
			this.index = index;
			this.item = item;
		}
	}

Example Usage:

		Arrays.asList("aaa", "bbb", "ccc").stream()
				.map(indexed())
				.forEach(o -> System.out.println(o.index + ":\t" + o.item));
	

Output:

   0:	aaa
   1:	bbb
   2:	ccc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment