Java .remove()

StevenSwiniarski's avatar
Published Jun 30, 2022
Contribute to Docs

The .remove() method removes an item from the underlying collection of an Iterator or a ListIterator object. This method removes the current element (i.e., the one returned by the last .next() or .previous() method).

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours

Syntax

iterator.remove();

Where iterator is an Iterator or ListIterator object.

Example

This example populates an ArrayList and then removes the even items with the .remove() method:

import java.util.*;
public class Example {
public static void main(String args[]) {
// Create a new ArrayList
ArrayList l = new ArrayList();
// Add some items to the ArrayList
l.add(1);
l.add(2);
l.add(3);
l.add(4);
l.add(5);
Iterator i = l.iterator();
// Loop through ArrayList contents
while(i.hasNext()) {
int item = (Integer) i.next();
// If item is even remove the element
if (item % 2 == 0) {
i.remove();
}
}
System.out.println(l);
}
}

This results in the following output:

[1, 3, 5]

All contributors

Contribute to Docs

Learn Java on Codecademy

  • Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
    • Includes 6 Courses
    • With Professional Certification
    • Beginner Friendly.
      75 hours
  • Learn to code in Java — a robust programming language used to create software, web and mobile apps, and more.
    • Beginner Friendly.
      17 hours