Given a list in Java, the task is to remove all the elements in the sublist whose index is between fromIndex, inclusive, and toIndex, exclusive. The range of the index is defined by the user.
Example:
Input list = [1, 2, 3, 4, 5, 6, 7, 8], fromIndex = 2, endIndex = 4
Output [1, 2, 5, 6, 7, 8]Input list = [‘G’, ‘E’, ‘E’, ‘G’, ‘G’, ‘K’, ‘S’], fromIndex = 3, endIndex = 5
Output [‘G’, ‘E’, ‘E’, ‘K’, ‘S’]
-
Method 1: Using subList() and clear() method
Syntax:
List.subList(int fromIndex, int toIndex).clear()
Example:
// Java code to remove a subList using
// subList(a, b).clear() method
Â
Âimport
java.util.*;
Â
Âpublic
class
AbstractListDemo {
   Â
public
static
void
main(String args[])
   Â
{
Â
ÂÂ Â Â Â Â Â Â Â
// Creating an empty AbstractList
       Â
AbstractList<String>
           Â
list =
new
LinkedList<String>();
Â
ÂÂ Â Â Â Â Â Â Â
// Using add() method
       Â
// to add elements in the list
       Â
list.add(
"GFG"
);
       Â
list.add(
"for"
);
       Â
list.add(
"Geeks"
);
       Â
list.add(
"computer"
);
       Â
list.add(
"portal"
);
Â
ÂÂ Â Â Â Â Â Â Â
// Output the list
       Â
System.out.println(
"Original List: "
                          Â
+ list);
Â
ÂÂ Â Â Â Â Â Â Â
// subList and clear method
       Â
// to remove elements
       Â
// specified in the range
       Â
list.subList(
1
,
3
).clear();
Â
ÂÂ Â Â Â Â Â Â Â
// Print the final list
       Â
System.out.println(
"Final List: "
                          Â
+ list);
   Â
}
}
Output:Original List: [GFG, for, Geeks, computer, portal] Final List: [GFG, computer, portal]
Note: Classes which can inherit AbstractList:
-
Method 2: Using removeRange() method
Syntax:
List.removeRange(int fromIndex, int toIndex)
Example:
// Java code to remove a subList
// using removeRange() method
Â
Âimport
java.util.*;
Â
Â// since removeRange() is a protected method
// ArrayList has to be extend the class
public
class
GFG
extends
ArrayList<Integer> {
Â
ÂÂ Â Â Â
public
static
void
main(String[] args)
   Â
{
Â
ÂÂ Â Â Â Â Â Â Â
// create an empty array list
Â
ÂÂ Â Â Â Â Â Â Â
GFG arr =
new
GFG();
Â
ÂÂ Â Â Â Â Â Â Â
// use add() method
       Â
// to add values in the list
       Â
arr.add(
1
);
       Â
arr.add(
2
);
       Â
arr.add(
3
);
       Â
arr.add(
4
);
       Â
arr.add(
5
);
       Â
arr.add(
6
);
       Â
arr.add(
7
);
       Â
arr.add(
8
);
Â
ÂÂ Â Â Â Â Â Â Â
// prints the list before removing
       Â
System.out.println(
"Original List: "
                          Â
+ arr);
Â
ÂÂ Â Â Â Â Â Â Â
// removing elements in the list
       Â
// from index 2 to 4
       Â
arr.removeRange(
2
,
4
);
       Â
System.out.println(
"Final List: "
                          Â
+ arr);
   Â
}
}
Output:Original List: [1, 2, 3, 4, 5, 6, 7, 8] Final List: [1, 2, 5, 6, 7, 8]