Remove Elements from ArrayList in Index Range

To remove elements from ArrayList present in the given Index Range, get those elements using subList() and then clear them using clear() method. You can call subList() method on the ArrayList, with from-index and to-index integer values passed as arguments respectively to the method.

Following is a quick code example to remove the elements from ArrayList in range [fromIndex, toIndex].

</>
Copy
boolean b = arraylist_1.subList(fromIndex, toIndex+1).clear;

One is added to toIndex argument of subList, because subList only considers the elements until toIndex but not including toIndex position.

There is a protected method ArrayList.removeRange() to remove all elements in the range. Since, the method is protected, we cannot use it publicly. But, if you create a subclass for ArrayList, then you can use removeRange() method.

Example 1 – Remove Elements from ArrayList in Given Index Range

In the following program, we shall take an ArrayList of strings, and remove all the elements present in the index range [1, 3].

Java Program

</>
Copy
import java.util.ArrayList;
import java.util.Arrays;

public class ArrayListExample {
	public static void main(String[] args) {
		ArrayList<String> arraylist_1 = new ArrayList<String>(
				Arrays.asList("apple", "banana", "mango", "orange", "papaya", "plum"));
				
		int fromIndex = 1;
		int toIndex = 3;
		arraylist_1.subList(fromIndex, toIndex+1).clear();
		
		arraylist_1.forEach(element -> {
			System.out.println(element);
		});
		
	}
}

Output

apple
papaya
plum

Conclusion

In this Java Tutorial, we learned how to remove all elements from the ArrayList present in the given range, using sublist() and clear() method.