javacodex.com
Java Examples
Java Examples
memu home questions

ArrayList Remove Elements By Name

This java example shows how to remove elements from an ArrayList by name rather then index.

Source: (ArrayListRemove.java)

import java.util.ArrayList;
 
public class ArrayListRemove { 
  public static void main(String[] args) { 
    ArrayList list = new ArrayList();
 
    list.add("John");
    list.add("Ringo");
    list.add("George");
    list.add("Paul");
 
    list.add("John");
 
    System.out.println("ArrayList Start: "+ list);
 
    // removes first occurrence
    list.remove("Ringo");
 
    System.out.println("ArrayList without Ringo: "+ list);
 
    // trick to remove all occurrences
    while(list.remove("John")) {}
 
    System.out.println("ArrayList without John: "+ list);
  } 
}
 

Output:

$ java ArrayListRemove
ArrayList Start: [John, Ringo, George, Paul, John]
ArrayList without Ringo: [John, George, Paul, John]
ArrayList without John: [George, Paul]

Contact: javacodex@yahoo.com