Remove element from list


From the list we can remove the element in two ways.
1. Remove the element on the basis of object index or position :
package net.raj.test;

import java.util.ArrayList;
import java.util.List;

public class ArrayListImpl {

    public static void main(String[] args) {
        // Declare an ArrayList
        List<String> list = new ArrayList<>();

        list.add("one");
        list.add("two");
        list.add("three");
        list.add("four");
        list.add("five");

        System.out.println("Sample ArrayList Before Removal :: " + list.toString());
       
        // remove the 1st element
        list.remove(0);
        System.out.println("Sample ArrayList After Removal :: " + list.toString());
       
    }
}

Output :
Sample ArrayList Before Removal :: [one, two, three, four, five]
Sample ArrayList After Removal :: [two, three, four, five]


2. Remove the element on the basis of object value :
package net.raj.test;

import java.util.ArrayList;
import java.util.List;

public class ArrayListImpl {

    public static void main(String[] args) {
        // Declare an ArrayList
        List<String> list = new ArrayList<>();

        list.add("one");
        list.add("two");
        list.add("three");
        list.add("four");
        list.add("five");

        System.out.println("Sample ArrayList Before Removal :: " + list.toString());
       
        // remove the element with value three
        list.remove("three");
        System.out.println("Sample ArrayList After Removal :: " + list.toString());
       
    }
}

Output :
Sample ArrayList Before Removal :: [one, two, three, four, five]
Sample ArrayList After Removal :: [one, two, four, five]

Look at my other posts:

Some other interesting blogs:

Comments

Popular posts from this blog

Custom Stack Implementation in java

List - Insertion order

Custom LinkedList Implementation