Replace an element from a Java List using ListIterator

Java 8Object Oriented ProgrammingProgramming

Let us first create a Java List and add elements −

ArrayList < String > list = new ArrayList < String > ();
list.add("Katie");
list.add("Tom");
list.add("Jack");
list.add("Amy");
list.add("Andre");
list.add("Brad");
list.add("Peter");
list.add("Bradley");

Now, use ListIterator and return the next element in the List with next() −

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

Replace the element in the List with set() method. Here, whatever element is set will get replaced as the first element of the Iterator −

iterator.set("Angelina");

Example

 Live Demo

import java.util.ArrayList;
import java.util.ListIterator;
public class Demo {
   public static void main(String[] args) {
      ArrayList<String>list = new ArrayList<String>();
      list.add("Katie");
      list.add("Tom");
      list.add("Jack");
      list.add("Amy");
      list.add("Andre");
      list.add("Brad");
      list.add("Peter");
      list.add("Bradley");
      System.out.println("Initial list..");
      for (String str: list) {
         System.out.println(str);
      }
      ListIterator<String>iterator = list.listIterator();
      iterator.next();
      iterator.set("Angelina");
      System.out.println("After replacing an element...");
      for (String str: list) {
         System.out.println(str);
      }
   }
}

Output

Initial list..
Katie
Tom
Jack
Amy
Andre
Brad
Peter
Bradley
After replacing an element...
Angelina
Tom
Jack
Amy
Andre
Brad
Peter
Bradley
raja
Published on 25-Apr-2019 08:58:47
Advertisements