使用 Guava,您可以使用Iterables.concat(Iterable<T> ...),它会创建所有可迭代对象的实时视图,并连接为一个(如果您更改可迭代对象,则连接版本也会更改)。然后用Iterables.unmodifiableIterable(Iterable<T>) 包装连接的可迭代对象(我之前没有看到只读要求)。
来自Iterables.concat( .. )JavaDocs:
将多个可迭代对象组合成一个
单个可迭代。返回的可迭代
有一个遍历
输入中每个可迭代的元素。
不轮询输入迭代器
直到必要。返回的
iterable 的迭代器支持remove()
当对应的输入迭代器
支持。
虽然这没有明确说明这是一个实时视图,但最后一句暗示它是(仅当支持迭代器支持 Iterator.remove() 方法时才支持它是不可能的,除非使用实时视图)
示例代码:
final List<Integer> first = Lists.newArrayList(1, 2, 3);
final List<Integer> second = Lists.newArrayList(4, 5, 6);
final List<Integer> third = Lists.newArrayList(7, 8, 9);
final Iterable<Integer> all =
Iterables.unmodifiableIterable(
Iterables.concat(first, second, third));
System.out.println(all);
third.add(9999999);
System.out.println(all);
输出:
[1、2、3、4、5、6、7、8、9]
[1、2、3、4、5、6、7、8、9、9999999]
编辑:
根据 Damian 的请求,这里有一个类似的方法,它返回一个实时的 Collection View
public final class CollectionsX {
static class JoinedCollectionView<E> implements Collection<E> {
private final Collection<? extends E>[] items;
public JoinedCollectionView(final Collection<? extends E>[] items) {
this.items = items;
}
@Override
public boolean addAll(final Collection<? extends E> c) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
for (final Collection<? extends E> coll : items) {
coll.clear();
}
}
@Override
public boolean contains(final Object o) {
throw new UnsupportedOperationException();
}
@Override
public boolean containsAll(final Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean isEmpty() {
return !iterator().hasNext();
}
@Override
public Iterator<E> iterator() {
return Iterables.concat(items).iterator();
}
@Override
public boolean remove(final Object o) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(final Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(final Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public int size() {
int ct = 0;
for (final Collection<? extends E> coll : items) {
ct += coll.size();
}
return ct;
}
@Override
public Object[] toArray() {
throw new UnsupportedOperationException();
}
@Override
public <T> T[] toArray(T[] a) {
throw new UnsupportedOperationException();
}
@Override
public boolean add(E e) {
throw new UnsupportedOperationException();
}
}
/**
* Returns a live aggregated collection view of the collections passed in.
* <p>
* All methods except {@link Collection#size()}, {@link Collection#clear()},
* {@link Collection#isEmpty()} and {@link Iterable#iterator()}
* throw {@link UnsupportedOperationException} in the returned Collection.
* <p>
* None of the above methods is thread safe (nor would there be an easy way
* of making them).
*/
public static <T> Collection<T> combine(
final Collection<? extends T>... items) {
return new JoinedCollectionView<T>(items);
}
private CollectionsX() {
}
}