public static < T > Set < T > filter ( final Set < ? extends T > input , final Condition < ? super T > condition , final int size ) { return new Set < T > ( ) { @ Override public int size ( ) { return size ; } @ Override public boolean isEmpty ( ) { return size == 0 ; } @ Override @ SuppressWarnings ( "unchecked" ) public boolean contains ( Object o ) { if ( ! input . contains ( o ) ) return false ; T elem = null ; try { elem = ( T ) o ; } catch ( ClassCastException cce ) { return false ; } /* * here's why the condition must be consistent with equals(): we * check it on the passed element while we really need to check * it on the element which is in the underlying set (and is * equal to o according to equals()). However, as long as the * condition is consistent, the result will be the same. */ return condition . holds ( elem ) ; } @ Override public Iterator < T > iterator ( ) { return filter ( input , condition ) . iterator ( ) ; } @ Override public Object [ ] toArray ( ) { Object [ ] result = new Object [ size ] ; int i = 0 ; for ( Object o : filter ( input , condition ) ) { result [ i ++ ] = o ; } return result ; } @ Override public < S > S [ ] toArray ( S [ ] a ) { throw new UnsupportedOperationException ( ) ; } @ Override public boolean add ( T e ) { throw new UnsupportedOperationException ( ) ; } @ Override public boolean remove ( Object o ) { throw new UnsupportedOperationException ( ) ; } @ Override public boolean containsAll ( Collection < ? > c ) { for ( Object o : c ) { if ( contains ( o ) ) return false ; } return true ; } @ Override public boolean addAll ( Collection < ? extends T > c ) { throw new UnsupportedOperationException ( ) ; } @ Override public boolean retainAll ( Collection < ? > c ) { throw new UnsupportedOperationException ( ) ; } @ Override public boolean removeAll ( Collection < ? > c ) { throw new UnsupportedOperationException ( ) ; } @ Override public void clear ( ) { throw new UnsupportedOperationException ( ) ; } } ; }
Returns read - only view of the given set consisting of the elements satisfying a given condition if the number of such elements is known