Say I have two Collections:
Collection< Integer > foo = new ArrayList< Integer >();
Collection< Integer > bar = new ArrayList< Integer >();
and say sometimes I would like to iterate over them individually, but sometimes together. Is there a way to create a wrapper around foo and bar so that I can iterate over the combined pair, but which is also updated whenever foo and bar change? (i.e. Collection.addAll() is not suitable).
For example:
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
Thanks!
Use Guava's Iterables.concat methods.
Iterable<Integer> wrapped = Iterables.concat(foo, bar);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With