Java .removeAll()
Anonymous contributor
Published May 21, 2024
Contribute to Docs
The .removeAll() method is used for removing multiple elements from instances of the ArrayList class.
Syntax
ArrayList1.removeAll(ArrayList2);
ArrayList1: It is theArrayListfrom which elements will be removed.ArrayList2: It is theArrayListcontaining the elements to be removed fromArrayList1.
Example
In the example below, two ArrayList instances, fallMonths and monthsToRemove, are created to hold String type elements. Elements are added to the fallMonths using the [.add()]
(https://www.codecademy.com/resources/docs/java/array-list/add) method. Then, monthsToRemove is utilized to remove the months - August and September from fallMonths using .removeAll(). Finally, all elements are removed from fallMonths by invoking .removeAll() with a reference to itself.
import java.util.ArrayList;public class RemoveFallMonths{public static void main(String[] args) {ArrayList<String> fallMonths = new ArrayList<String>();fallMonths.add("August");fallMonths.add("September");fallMonths.add("October");fallMonths.add("November");fallMonths.add("December");ArrayList<String> monthsToRemove = new ArrayList<String>();monthsToRemove.add("August");monthsToRemove.add("December");// Remove August and December from fallMonths using monthsToRemovefallMonths.removeAll(monthsToRemove);System.out.println("After removing specified months: " + fallMonths);// Remove all elements from fallMonthsfallMonths.removeAll(fallMonths);System.out.println("After removing all elements: " + fallMonths);}}
The output of the above code should look like this:
After removing specified months: [September, October, November]After removing all elements: []
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve 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