java arraylist remove
// how to remove element from arraylist in java while iterating
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ArrayListWhileIterating
{
public static void main(String[] args)
{
List<String> fruits = new ArrayList<>();
fruits.add("grapes");
fruits.add("pineapple");
fruits.add("apple");
fruits.add("mango");
fruits.add("banana");
fruits.add("orange");
// before removing any element
System.out.println("Before - remove element from arraylist while iterating: ");
System.out.println(fruits);
Iterator<String> itr = fruits.iterator();
while(itr.hasNext())
{
String strFruit = itr.next();
if(strFruit.equals("apple"))
{
itr.remove();
}
}
// after removing an element
System.out.println("After - remove element from arraylist while iterating: ");
System.out.println(fruits);
}
}
// how to remove all elements from arraylist in java
import java.util.ArrayList;
public class RemoveAllElements
{
public static void main(String[] args)
{
ArrayList<String> fruits = new ArrayList<>();
fruits.add("pineapple");
fruits.add("orange");
fruits.add("apple");
fruits.add("banana");
fruits.add("watermelon");
System.out.println("ArrayList before using clear() method: ");
System.out.println(fruits);
// empty an ArrayList using clear() method
fruits.clear();
System.out.println("ArrayList after using clear() method: ");
System.out.println(fruits);
ArrayList<String> colors = new ArrayList<>();
colors.add("red");
colors.add("blue");
colors.add("green");
colors.add("white");
System.out.println("ArrayList before using removeAll() method: ");
System.out.println(colors);
// empty an ArrayList using removeAll() method
colors.removeAll(colors);
System.out.println("ArrayList after using removeAll() method: ");
System.out.println(colors);
}
}
// Java.util.ArrayList.remove(Object) method example
import java.util.ArrayList;
import java.util.List;
public class ArrayListRemoveObjectMethod
{
public static void main(String[] args)
{
List<Integer> al = new ArrayList<>();
al.add(56);
al.add(28);
al.add(39);
al.add(59);
al.add(82);
System.out.println("Before using ArrayList.remove(Object) method size of ArrayList: " + al);
// removes element 56
al.remove(new Integer(56));
// removes element 28
al.remove(new Integer(28));
System.out.println("After using ArrayList.remove(Object) method size of ArrayList: " + al);
}
}
// java program on ArrayList remove(int index) method example
import java.util.ArrayList;
import java.util.List;
public class ArrayListRemoveIndex
{
public static void main(String[] args)
{
List<Integer> al = new ArrayList<>();
al.add(56);
al.add(28);
al.add(39);
al.add(59);
al.add(82);
System.out.println("Before using ArrayList.remove(int index) method: " + al);
// removes element 28
al.remove(1);
// element 39 is now moved one position back
// So element 39 is removed
al.remove(1);
System.out.println("After using ArrayList.remove(int index) method: " + al);
}
}