我前一陣子放在一起JoinedArray
類,可以幫助。如果你不想經常這樣做,這有點矯枉過正,但如果你在代碼中做了這麼多,你可能會發現它有用。
它實際上並沒有將這些數組連接到一個新的數組中 - 它實際上提供了一個Iterable
,然後可以遍歷連接的數組。
public class JoinedArray<T> implements Iterable<T> {
final List<T[]> joined;
@SafeVarargs
public JoinedArray(T[]... arrays) {
joined = Arrays.<T[]>asList(arrays);
}
@Override
public Iterator<T> iterator() {
return new JoinedIterator<>(joined);
}
private class JoinedIterator<T> implements Iterator<T> {
// The iterator across the arrays.
Iterator<T[]> i;
// The array I am working on.
T[] a;
// Where we are in it.
int ai;
// The next T to return.
T next = null;
private JoinedIterator(List<T[]> joined) {
i = joined.iterator();
a = i.hasNext() ? i.next() : null;
ai = 0;
}
@Override
public boolean hasNext() {
while (next == null && a != null) {
// a goes to null at the end of i.
if (a != null) {
// End of a?
if (ai >= a.length) {
// Yes! Next i.
if (i.hasNext()) {
a = i.next();
} else {
// Finished.
a = null;
}
ai = 0;
}
if (a != null) {
if (ai < a.length) {
next = a[ai++];
}
}
}
}
return next != null;
}
@Override
public T next() {
T n = null;
if (hasNext()) {
// Give it to them.
n = next;
next = null;
} else {
// Not there!!
throw new NoSuchElementException();
}
return n;
}
@Override
public void remove() {
throw new UnsupportedOperationException("Not supported.");
}
}
public static void main(String[] args) {
JoinedArray<String> a = new JoinedArray<>(
new String[]{
"Zero",
"One"
},
new String[]{},
new String[]{
"Two",
"Three",
"Four",
"Five"
},
new String[]{
"Six",
"Seven",
"Eight",
"Nine"
});
for (String s : a) {
System.out.println(s);
}
}
}
嗯,這是一個班輪。我不確定我會說這是*簡單*因此...... – 2015-02-23 13:27:30
您可能想用'Stream.of(「d」,「e」,「f」)替換'Arrays.stream(EXTENDED)' '。另一種選擇:'private static String [] EXTENDED = Stream.of(BASE,new String [] {「d」,「e」,「f」})。flatMap(Arrays :: stream).toArray(String []: :new);'雖然不如'concat'短。 – 2015-02-23 13:32:18
@JonSkeet你是對的。 Java 8仍然是相當新的,並且很多人都沒有對流API進行充分的探索。 – 2015-02-23 17:57:40