将多个Iterables包装到单个Interable中

Dun*_*nie 3 java collections

说我有两个Collections:

Collection< Integer > foo = new ArrayList< Integer >();
Collection< Integer > bar = new ArrayList< Integer >();
Run Code Online (Sandbox Code Playgroud)

并说有时我想单独迭代它们,但有时一起.有没有一种方法围绕创建一个包装foo,并bar让我可以在联合对迭代,但也随时更新foobar改变?(即Collection.addAll()不适合).

例如:

Collection< Integer > wrapper = ... // holds references to both bar and foo

foo.add( 1 );
bar.add( 99 );

for( Integer fooInt : foo ) {
    System.out.println( fooInt );
} // output: 1

for( Integer barInt : bar ) {
    System.out.println( barInt );
} // output: 99

for( Integer wrapInt : wrapper ) {
    System.out.println( wrapInt );
} // output: 1, 99

foo.add( 543 );

for( Integer wrapInt : wrapper ) {
    System.out.println( wrapInt );
} // output: 1, 99, 543
Run Code Online (Sandbox Code Playgroud)

谢谢!

Col*_*inD 5

使用GuavaIterables.concat方法.

Iterable<Integer> wrapped = Iterables.concat(foo, bar);
Run Code Online (Sandbox Code Playgroud)