Java Program to remove an element from List with ListIterator

Java 8Object Oriented ProgrammingProgramming

Let’s say the following is our List with elements −

ArrayList < String > arrList = new ArrayList < String > ();
arrList.add("Jack");
arrList.add("Tom");
arrList.add("Brad");
arrList.add("Amy");
arrList.add("Ben");
arrList.add("Peter");
arrList.add("Katie");
arrList.add("Tim");

Now, use the listIterator(). The next() method returns the next element in the List. Hoverer,remove an element using remove() method −

ListIterator<String>iterator = arrList.listIterator();
iterator.next();
iterator.remove();

Example

 Live Demo

import java.util.ArrayList;
import java.util.ListIterator;
public class Demo {
   public static void main(String[] args) {
      ArrayList<String>arrList = new ArrayList<String>();
      arrList.add("Jack");
      arrList.add("Tom");
      arrList.add("Brad");
      arrList.add("Amy");
      arrList.add("Ben");
      arrList.add("Peter");
      arrList.add("Katie");
      arrList.add("Tim");
      System.out.println("List...");
      for (String str: arrList) {
         System.out.println(str);
      }
      ListIterator<String>iterator = arrList.listIterator();
      iterator.next();
      iterator.remove();
      System.out.println("Updated List...");
      for (String str: arrList) {
         System.out.println(str);
      }
   }
}

Output

List...
Jack
Tom
Brad
Amy
Ben
Peter
Katie
Tim
Updated List...
Tom
Brad
Amy
Ben
Peter
Katie
Tim
raja
Published on 24-Apr-2019 15:07:19
Advertisements