In this example, let us see how to remove elements from LinkedList by specifying the range with sublist and clear methods in Java.
Source Code
package com.beginner.examples;
import java.util.LinkedList;
public class RemoveRangeElementsLinkedList {
public static void main(String[] args) {
//create LinkedList.
LinkedList linkedList = new LinkedList();
linkedList.add("A");
linkedList.add("B");
linkedList.add("C");
linkedList.add("D");
linkedList.add("E");
System.out.println("Before remove, LinkedList is : " + linkedList);
//remove elements from index 2(inclusive) to 5(exclusive).
linkedList.subList(2,5).clear();
System.out.println("After remove, LinkedList is : " + linkedList);
}
}
Output:
Before remove, LinkedList is : [A, B, C, D, E]
After remove, LinkedList is : [A, B]
References
Imported packages in Java documentation: