How do I remove something from a List in Java?

The ArrayList.remove(int index) method to remove element from ArrayList. Remove method is overloaded.

  1. ArrayList.remove(E element) remove the element at specifid index.
  2. ArrayList.remove(E element) remove the element by value.
  3. ArrayList.removeIf(Predicate p) remove all elements by specified value.

1. ArrayList.remove(int index) remove element from arraylist at specified index

This method removes the specified element E at the specified position in this list. It removes the element currently at that position and all subsequent elements are moved to the left (will subtract one to their indices).

Index start with 0.

public class ArrayListExample { public static void main(String[] args) { ArrayList namesList = new ArrayList(Arrays.asList( "alex", "brian", "charles") ); System.out.println(namesList); //list size is 3 //Add element at 1 index namesList.remove(1); System.out.println(namesList); //list size is 2 } }

Program output.

[alex, brian, charles] [alex, charles]

2. ArrayList.remove(E element) remove element from arraylist by element value

This method removes the first occurrence of specified element E in this list. As this method removes the custom object, the list size decreases by one.

Index start with 0.

public class ArrayListExample { public static void main(String[] args) { ArrayList namesList = new ArrayList(Arrays.asList( "alex", "brian", "charles", "alex") ); System.out.println(namesList); namesList.remove("alex"); System.out.println(namesList); } }

Program output.

[alex, brian, charles, alex] [brian, charles, alex]

3. Remove all element from arraylist by value

ArrayList does not provide inbuilt method to remove all elements by specified value. We can use other super easy syntax from Java 8 stream to remove all elements for given element value.

Java program to use List.removeIf() for how to remove multiple elements from arraylist in java by element value.

public class ArrayListExample { public static void main(String[] args) { ArrayList namesList = new ArrayList(Arrays.asList( "alex", "brian", "charles", "alex") ); System.out.println(namesList); namesList.removeIf( name -> name.equals("alex")); System.out.println(namesList); } }

Program output.

[alex, brian, charles, alex] [brian, charles]

Happy Learning !!

Read More:

A Guide to Java ArrayList
ArrayList Java Docs

Let us know if you liked the post. Thats the only way we can improve.

Video liên quan

0 nhận xét: