3 回答
TA贡献1811条经验 获得超5个赞
这可能是您问题的错误答案。在这种情况下,我会删除它,但也许您可以将它用于您想要实现的目标:
int[][] it = {{1,2}, {3,4,5}};
OfInt iterator = Arrays.stream(it).flatMapToInt(x -> IntStream.of(x)).iterator();
iterator.forEachRemaining((IntConsumer) System.out::print);
流式传输锯齿状数组,将其平面映射为一个IntStream,然后用它做你想做的事。在这个例子中,我获取了迭代器,但你可能只想要:
Arrays.stream(it).flatMapToInt(x -> IntStream.of(x)).forEach((IntConsumer) System.out::print);
在forEach你可以做你需要的,或使用其他一些方法IntStream
TA贡献1946条经验 获得超4个赞
公共类 IteratorFor2DArray 实现 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;
}
}
TA贡献2039条经验 获得超7个赞
我还找到了另一种方法:
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);
}
}
添加回答
举报