private static < T extends Comparable < T > > Optional < Range < T > > smallestContainerForRange ( Collection < Range < T > > ranges , Range < T > target ) { Range < T > best = Range . all ( ) ; for ( final Range < T > r : ranges ) { if ( r . equals ( target ) ) { continue ; } // prefer a smaller range, always; if ( r . encloses ( target ) && best . encloses ( r ) ) { best = r ; } } if ( best . equals ( Range . < T > all ( ) ) ) { return Optional . absent ( ) ; } return Optional . of ( best ) ; }
Assuming our ranges look tree - structured finds the smallest range for the particular target one .