To remove element from List via ListIterator in Java
//get ListIterator ListIterator<String> litr = al.listIterator(); while(litr.hasNext()) { String element = litr.next(); if("CSS".equals(element)) { //remove element litr.remove(); //from w ww . j av a2s . c om } }
Full source
import java.util.ArrayList; import java.util.List; import java.util.ListIterator; public class Main { public static void main(String args[]) { // Create an array list. List<String> al = new ArrayList<String>(); //from w w w . ja v a2s.c om // Add elements to the array list. al.add("SQL"); al.add("CSS"); al.add("Java"); al.add("Javascript"); al.add("CSS"); al.add("HTML"); al.add("Demo2s.com"); al.add("CSS"); al.add(1, "Hi"); System.out.println(al); ListIterator<String> litr = al.listIterator(); while(litr.hasNext()) { String element = litr.next(); if("CSS".equals(element)) { litr.remove(); } } System.out.println(al); } }
import java.util.ArrayList; import java.util.List; import java.util.ListIterator; public class Main { public static void main(String args[]) { List<String> langList = new ArrayList<>(); langList.add("CSS"); langList.add("Java"); langList.add("Javascript"); langList.add("SQL"); langList.add("C++"); langList.add("HTML"); ListIterator<String> lit = langList.listIterator(); //from w ww . j ava 2 s . com System.out.println(lit.next()); String s = (String) lit.next(); System.out.println(s); lit.remove(); System.out.println(lit.next()); lit.add(s); System.out.println(lit.next());// Gets back just added System.out.println(lit.previous()); s = (String) lit.previous(); lit.remove(); System.out.println(lit.next()); lit.add(s); } }