Friday 10 October 2014

Java : Collection Framework : ArrayList (Remove Objects)
























Click here to watch in Youtube : https://www.youtube.com/watch?v=R5e1rgrHsd8

ArrayListRemoveExample.java
import java.util.ArrayList;

/*
 * Example of remove(int index) and remove(Object o) methods
 */
public class ArrayListRemoveExample
{

    public static void main(String[] args)
    {
        ArrayList<String> arrayList = new ArrayList<String>();
        arrayList.add("Ram");
        arrayList.add("Dave");
        arrayList.add("Peter");
        arrayList.add("Julia");
        arrayList.add("Akram");

        System.out.println("ArrayList : " + arrayList + "\n");

        /*
         * Remove element from the index position 1.
         */

        arrayList.remove(1);

        System.out.println("ArrayList after removing element from the index 1 : "
                + arrayList + "\n");

        /*
         * Remove the String object Julia.
         */

        arrayList.remove("Julia");

        System.out.println("ArrayList after removing String object \"Julia\" : "
                + arrayList);
    }

}

Output
ArrayList : [Ram, Dave, Peter, Julia, Akram]

ArrayList after removing element from the index 1 : [Ram, Peter, Julia, Akram]

ArrayList after removing String object "Julia" : [Ram, Peter, Akram]

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

/*
 * Example of removeAll(Collection<?> c) method
 */
public class ArrayListRemoveAllExample
{

    public static void main(String[] args)
    {
        ArrayList<String> arrayList = new ArrayList<String>();
        arrayList.add("Ram");
        arrayList.add("Dave");
        arrayList.add("Peter");
        arrayList.add("Julia");
        arrayList.add("Akram");

        System.out.println("ArrayList : " + arrayList + "\n");

        List<String> removeList = new ArrayList<String>();
        removeList.add("Dave");
        removeList.add("Peter");

        System.out.println("RemoveList : " + removeList + "\n");

        /*
         * Remove group of elements from the list
         */

        arrayList.removeAll(removeList);

        System.out
                .println("ArrayList after removing elements which are present in the removeList : "
                        + arrayList + "\n");

    }

}

Output
ArrayList : [Ram, Dave, Peter, Julia, Akram]

RemoveList : [Dave, Peter]

ArrayList after removing elements which are present in the removeList : [Ram, Julia, Akram]

To Download ArrayListDemoRemove Project Click the below link

https://sites.google.com/site/javaee4321/java-collections/ArrayListDemoRemove.zip?attredirects=0&d=1

See also:

  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • No comments:

    Post a Comment