Monday, 18 May 2015

How to use retailAll in LinkedList

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.LinkedList;
import java.util.List;

public class RetainAll {

    public static void main(String[] args) {
       
        LinkedList<String> linkedList = new LinkedList<String>();
       
        linkedList.add("Mumbai");
        linkedList.add("Delhi");
        linkedList.add("Noida");
        linkedList.add("Gao");
        linkedList.add("Patna");
        //print linkedlist
        System.out.println(" Linklist is = "+linkedList);
       
        List<String> brr = new LinkedList<String>();
       
        brr.add("Delhi");
        brr.add("KKR");
       
        /*
         * Retains only the elements in linkedlist
         * collection that are contained in the brr
         */
       
       
        linkedList.retainAll(brr);
       
        System.out.println("After retainAll linkedlist is= "+linkedList);
       
       
    }
   
   
}

Output:

 Linklist is = [Mumbai, Delhi, Noida, Gao, Patna]

 After retainAll linkedlist is= [Delhi]

No comments:

Post a Comment