Java ListIterator replace element in List

Description

Java ListIterator replace element in List


import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

public class Main {
  public static void main(String[] args) {
    // add colors elements to list1
    String[] colors = { "css", "java", "javacript" };
    List<String> list1 = new LinkedList<>();

    for (String color : colors)
      list1.add(color);/*from w w  w  . j  a va  2 s .  c o m*/
    System.out.println(list1);
    ListIterator<String> iterator = list1.listIterator();

    while (iterator.hasNext()) {
      String color = iterator.next(); // get item
      iterator.set(color.toUpperCase()); // convert to upper case
    }
    System.out.println(list1);
  }

}
import java.util.List;
import java.util.ArrayList;
import java.util.ListIterator;

public class Main {
  public static void main(String[] args) {
    List<String> aList = new ArrayList<String>();

    aList.add("CSS");
    aList.add("HTML");
    aList.add("Java");
    aList.add("C++");
    aList.add("demo 2s .com");

    ListIterator<String> listIterator = aList.listIterator();
    listIterator.next();//from  w w  w . j a  v a2  s. c  o  m

    listIterator.set("new added value");
    for (String str : aList) {
      System.out.println(str);
    }
  }
}



PreviousNext

Related