First of all sort all the given ranges
Collections . sort ( ranges , new Comparator < Pair > ( ) { public int compare ( Pair first , Pair second ) { if ( first . first == second . first ) { return first . second - second . second ; } return first . first - second . first ; } } ) ;