Java Collection How to - Remove a Single Element








Question

We would like to know how to remove a Single Element.

Answer

Use the remove() method to remove a single element:

If the list contains duplicates, the first element in the list that matches the element will be removed.

If removal is not supported, you'll get an UnsupportedOperationException.

If the index passed in is outside the valid range of elements, an IndexOutOfBoundsException is thrown.

import java.util.ArrayList;
import java.util.List;
//from  w  w  w  .j  a v a 2 s.  c om
public class MainClass {
  public static void main(String args[]) throws Exception {

    List list = new ArrayList();
    list.add("A");
    list.add("B");
    list.add("C");

    System.out.println(list.remove(0));
    System.out.println(list.remove("B"));
    System.out.println(list);

  }
}

The code above generates the following result.

Remove actual object from a list in Java

/*from   www . j a  va2 s .  c o m*/
import java.util.ArrayList;

public class Main {
  public static void main(String[] a) {
    ArrayList<Employee> emps = new ArrayList<Employee>();

    Employee emp1 = new Employee("A", "G");
    Employee emp2 = new Employee("T", "A");
    Employee emp3 = new Employee("K", "J");

    emps.add(emp1);
    emps.add(emp2);
    emps.add(emp3);

    System.out.println(emps);

    emps.remove(emp2);

    System.out.println(emps);
  }
}

class Address {
}

class Employee {
  private String lastName;

  private String firstName;

  private Double salary;

  public Address address;

  public Employee(String lastName, String firstName) {
    this.lastName = lastName;
    this.firstName = firstName;
    this.address = new Address();

  }

  public String getLastName() {
    return this.lastName;
  }

  public void setLastName(String lastName) {
    this.lastName = lastName;
  }

  public String getFirstName() {
    return this.firstName;
  }

  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }

  public double getSalary() {
    return this.salary;
  }

  public void setSalary(double salary) {
    this.salary = salary;
  }
}

The code above generates the following result.