Remove a range of elements from a LinkedList in Java

Java 8Object Oriented ProgrammingProgramming

A range of elements can be removed from a LinkedList by using the method java.util.LinkedList.clear() along with the method java.util.LinkedList.subList(). A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.LinkedList;
public class Demo {
   public static void main(String[] args) {
      LinkedList<String> l = new LinkedList<String>();
      l.add("Clark");
      l.add("Bruce");
      l.add("Diana");
      l.add("Wally");
      l.add("Oliver");
      System.out.println("The LinkedList is: " + l);
      l.subList(1,3).clear();
      System.out.println("The LinkedList is: " + l);
   }
}

Output

The LinkedList is: [Clark, Bruce, Diana, Wally, Oliver]
The LinkedList is: [Clark, Wally, Oliver]

Now let us understand the above program.

The LinkedList l is created. Then LinkedList.add() is used to add the elements to the LinkedList. Then the LinkedList is displayed. A code snippet which demonstrates this is as follows −

LinkedList<String> l = new LinkedList<String>();
l.add("Clark");
l.add("Bruce");
l.add("Diana");
l.add("Wally");
l.add("Oliver");
System.out.println("The LinkedList is: " + l);

A range of elements from index 1(inclusive) to index 3(exclusive) are removed from the LinkedList using the LinkedList.clear() and the LinkedList.subList() methods. Then the modified LinkedList is displayed. A code snippet which demonstrates this is as follows −

System.out.println("The LinkedList is: " + l);
l.subList(1,3).clear();
System.out.println("The LinkedList is: " + l);
raja
Published on 16-Jan-2019 11:13:40
Advertisements