How can I override next() for jagged array java?

I have a jagged array. How can I override next(), so I can get its elements step-by-step?

728x90

3 Answers How can I override next() for jagged array java?

This might be a wrong answer to your question. I'll remove it in that case, but maybe you can use it for what you want to achieve:

int[][] it = {{1,2}, {3,4,5}};

OfInt iterator = Arrays.stream(it).flatMapToInt(x -> IntStream.of(x)).iterator();
iterator.forEachRemaining((IntConsumer) System.out::print);

Stream the jagged array, flatmap it into one single IntStream and then do what you want with it. In this example I fetched the iterator but you might only want:

Arrays.stream(it).flatMapToInt(x -> IntStream.of(x)).forEach((IntConsumer) System.out::print); 

In forEach you can do what you need, or use some other method of IntStream

7 months ago

Thank you all for your answers, I've found my answer in russian stackoverflow: https://ru.stackoverflow.com/questions/867881/java-iterator-%D0%B4%D0%BB%D1%8F-%D0%BC%D0%BD%D0%BE%D0%B3%D0%BE%D0%BC%D0%B5%D1%80%D0%BD%D0%BE%D0%B3%D0%BE-%D0%BC%D0%B0%D1%81%D1%81%D0%B8%D0%B2%D0%B0

public class IteratorFor2DArray implements Iterator {

private int size;
private int i = 0;
private int j = 0;
private int[][] values = new int[i][j];
private int position = 0;

public IteratorFor2DArray(int[][] values) {
    this.values = values;
    this.size = countOfElements(values);
}

private int countOfElements(int[][] values) {
    int count = 0;
    for (int[] row : values) {
        count += row.length;
    }
    return count;
}

@Override
public boolean hasNext() {
    return position < size;
}

@Override
public Integer next() {
    if (position >= size) {
        throw new NoSuchElementException();
    }
    int element = values[i][j];
    position++;
    j++;
    while (i < values.length && j >= values[i].length) {
        j = 0;
        i++;
    }
    return element;
}

}

7 months ago

I've also found another way:

public class IteratorFor2DArray implements Iterator {

    private int[][] data;
    private int i, j;

    public IteratorFor2DArray(int[][] data) {
        this.data = data;
    }

    @Override
    public Integer next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        int element = data[i][j];
        j++;
        while (i < data.length && j >= data[i].length) {
            j = 0;
            i++;
        }
        return element;
    }

    @Override
    public boolean hasNext() {
        return (i < data.length && j < data[i].length);
    }
}

6 months ago