public static < T > Iterable < T > compose ( final Iterable < Iterable < T > > iterables ) { return toIterable ( new Iterator < T > ( ) { Iterator < Iterable < T > > it = iterables . iterator ( ) ; Iterator < T > current = null ; T next = null ; @ Override public boolean hasNext ( ) { if ( next != null ) { return true ; } else { if ( ( current == null || ! current . hasNext ( ) ) && it . hasNext ( ) ) { while ( it . hasNext ( ) && ( current == null || ! current . hasNext ( ) ) ) { Iterable < T > nextIt = it . next ( ) ; if ( nextIt != null ) { current = nextIt . iterator ( ) ; } } } if ( current != null && current . hasNext ( ) ) { next = current . next ( ) ; return true ; } } return false ; } @ Override public T next ( ) { if ( hasNext ( ) ) { T result = next ; next = null ; return result ; } else { throw new NoSuchElementException ( ) ; } } @ Override public void remove ( ) { throw new UnsupportedOperationException ( "Remove is not supported" ) ; } } ) ; }
Given a number of iterables construct a iterable that iterates all of the iterables .