@ SuppressWarnings ( "unchecked" ) public < A > A [ ] toArray ( A [ ] emptyArray ) { if ( emptyArray . length != 0 ) { throw new IllegalArgumentException ( "Empty array must be supplied" ) ; } return stream ( ) . toArray ( size -> size == 0 ? emptyArray : ( A [ ] ) Array . newInstance ( emptyArray . getClass ( ) . getComponentType ( ) , size ) ) ; }
Returns an array containing all the stream elements . If the stream happens to contain no elements the supplied empty array is returned instead . Otherwise the new array is allocated which element type is the same as the element type of supplied empty array .