Search code examples
javaiterator

Returns each array element 2 times using Iterator


I have a method public static Iterator<Integer> intArrayTwoTimesIterator(int[] array) that take an array. I need to returns an Iterator that iterates over given array but returns each array element 2 times. For exemple array is new int[]{1, 2, 3}, and in output need to be "[1, 1, 2, 2, 3, 3]". How to return elements 2 times using Iterator?


Solution

  • You can try this implementation:

    public static Iterator<Integer> intArrayTwoTimesIterator(int[] array) {
      return Arrays.stream(array).
              flatMap(value -> IntStream.of(value, value)).
              boxed().iterator();
    }