Sunday 10 May 2015

How to use retailAll in arraylist

Retains only the elements in this list that are contained in the specified collection. In other words, removes from this list all of its elements that are not contained in the specified collection.


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

public class RetainAll {
   
    public static void main(String[] args) {
        ArrayList<String> arr = new ArrayList<String>();
       
        // add element in arraylist
       
        arr.add("c");
        arr.add("php");
        arr.add("html");
        arr.add("java");
        arr.add("delhi");
        arr.add("INDIA");
       
        // print arraylist
       
        System.out.println("arrayList is = " + arr);
   
        List<String> brr = new ArrayList<String>();
       
        brr.add("java");
        brr.add("shivam");
       
        /*
         *  removes from arr all of its elements that are
         *  not contained  in the brr.
         */
       
        arr.retainAll(brr);
       
        System.out.println("After retainAll arr is="+arr);
       
    }

}

 Output:

arrayList is = [c, php, html, java, delhi, INDIA]

After retainAll arr is=[java]


Related Posts: 

 


Storing Java Object In ArrayList






No comments:

Post a Comment