Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapping multiple Iterables into a single Interable

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!

like image 408
Matt Dunn Avatar asked Nov 16 '25 05:11

Matt Dunn


1 Answers

Use Guava's Iterables.concat methods.

Iterable<Integer> wrapped = Iterables.concat(foo, bar);
like image 185
ColinD Avatar answered Nov 18 '25 18:11

ColinD