- Given an arraylist containing string objects, we would like to remove or delete elements from arraylist collection.
- Arraylist has following methods to remove or delete element(s)/nodes/objects.
No. | Method name | Description |
---|---|---|
1 | E remove(int index) | Removes the element at the specified position in this list. |
2 | boolean remove(Object o) | Removes the first occurrence of the specified element from this list, if it is present. |
3 | boolean removeAll(Collection<?> c) | Removes from this list all of its elements that are contained in the specified collection. |
Program – remove or delete elements/nodes from arraylist in java
package org.learn.collection.list.arrayList; import java.util.ArrayList; public class DemoRemoveInArrayList { public static void main(String[] args) { ArrayList<String> arrayList = new ArrayList<>(); arrayList.add( "archery" ); arrayList.add( "badminton" ); arrayList.add( "canoe" ); arrayList.add( "boxing" ); arrayList.add( "diving" ); arrayList.add( "cycling" ); arrayList.add( "rowing" ); System.out.println( "Demo of remove methods: " ); demoRemoveMethod(arrayList); } private static void demoRemoveMethod(ArrayList<String> arrayList) { // [archery, badminton, canoe, boxing, diving, cycling, rowing] System.out.println( "1. Orignal ArrayList:" + arrayList); // Remove element by index arrayList.remove( 0 ); // [badminton, canoe, boxing, diving, cycling, rowing] System.out.println( "2. Removed element at 0 index: " + arrayList); // Remove element after comparing and remove it arrayList.remove( "boxing" ); // [badminton, canoe, diving, cycling, rowing] System.out.println( "3. Removed boxing from arrayList: " + arrayList); ArrayList<String> removeElementsList = new ArrayList<>(); removeElementsList.add( "canoe" ); removeElementsList.add( "diving" ); // Remove element by supplying another collection arrayList.removeAll(removeElementsList); // [badminton, cycling, rowing] System.out.println( "4. Removed collection containing canoe and diving: " + arrayList); } } |
Output – remove or delete objects/nodes from arraylist collection in java
Demo of remove methods: 1. Orignal ArrayList:[archery, badminton, canoe, boxing, diving, cycling, rowing] 2. Removed element at 0 index: [badminton, canoe, boxing, diving, cycling, rowing] 3. Removed boxing from arrayList: [badminton, canoe, diving, cycling, rowing] 4. Removed collection containing canoe and diving: [badminton, cycling, rowing] |