[英]Iterate through a 2D array as if it were a 1D array using Iterator
我是Java的初學者,我必須從Iterator<Iterator<Integer>>
這樣的東西中獲取值。 例如,我們可能有:
{{1, 2}, {3, 4}, {5, 6}}
next()
的結果應為1
。 如果我們試圖next()
一個更多的時間- 2
,然后- 3
, 4
等喜歡由一個從一維陣列的一個得到的值,但來自2D陣列。 我們不應該復制任何東西。 所以,我在下面寫了一些不好的代碼:
public class IteratorNext {
private Iterator<Iterator<Integer>> values = null;
private Iterator<Integer> current;
public IteratorNext(Iterator<Iterator<Integer>> iterator) {
this.values = iterator;
}
public int next() throws NoSuchElementException {
current = values.next();
if (!current.hasNext()) {
values.next();
}
if (!values.hasNext() && !current.hasNext()) {
throw new NoSuchElementException("Reached end");
}
return current.next();
}
}
該代碼是不正確的,因為結果next()
為1
,則3
,那么5
因為這里異常的。 如何解決這個問題?
如果您使用的是Java-8 ,則可以利用flatMapToInt
函數將2D數組array2d
為1D數組(可以將array2d
視為對2D數組的引用):
Arrays.stream(array2d).flatMapToInt(Arrays::stream).forEach(System.out::println);
如果您想堅持自己的解決方案,則需要修改next
方法,如下所示:
public int next() throws NoSuchElementException {
int result = -1;
//Are we already iterating one of the second dimensions?
if(current!=null && current.hasNext()) {
//get the next element from the second dimension.
result = current.next();
} else if(values != null && values.hasNext()) {
//get the next second dimension
current = values.next();
if (current.hasNext()) {
//get the next element from the second dimension
result = current.next();
}
} else {
//we have iterated all the second dimensions
throw new NoSuchElementException("Reached end");
}
return result;
}
public static class IteratorNext {
private Iterator<Iterator<Integer>> values = null;
private Iterator<Integer> current;
public IteratorNext(Iterator<Iterator<Integer>> iterator) {
this.values = iterator;
}
public int next() throws NoSuchElementException {
if (current != null && current.hasNext()) {
Integer val = current.next();
return val;
}
if (values != null && values.hasNext()) {
current = values.next();
if (current != null && current.hasNext()) {
Integer val = current.next();
return val;
}
}
throw new NoSuchElementException("Reached end");
}
}
每次調用next()時,都必須處理結果。
next()方法的第一行會跳過第一個元素,因為您在next()方法的末尾調用current.next()。
一般來說,此代碼不是處理集合的正確方法。 您必須根據使用情況分析問題。
問題是每次調用next()時,您都從
current = values.next();
因此,在每次調用時,您都跳到下一個迭代器,而無需嘗試繼續當前迭代。
相反,您應該做類似的事情
if(!current.hasNext())
current = values.next();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.