Iterables { public static <T> Iterable<T> take(final Iterable<T> iterable, final int elementCount) { return new Iterable<T>() { @Override public Iterator<T> iterator() { return new LengthIterator<>(iterable.iterator(), elementCount); } }; }  static Iterable<T> concatenate(Iterable<T>... iterables); static Iterable<T> take(final Iterable<T> iterable, final int elementCount);  }
@Test public void testTakeReturnsTheFirstNElementsOfAnIterable() { Iterable<Integer> someIterable = Arrays.asList(1, 2, 3, 4, 5); Iterable<Integer> firstElements = Iterables.take(someIterable, 3); assertThat(firstElements, hasItems(1, 2, 3)); }
@Test public void testTakeReturnsNoMoreThanNElements() { int elementsToTake = 3; Iterable<Integer> someIterable = Arrays.asList(1, 2, 3, 4, 5); Iterable<Integer> firstElements = Iterables.take(someIterable, elementsToTake); int takenElements = 0; for (Integer element : firstElements) { takenElements++; } assertThat(takenElements, is(elementsToTake)); }