Java LinkedList retainAll() method with Examples

This example shows Java LinkedList retainAll() method with Examples . 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]

We have seen Java LinkedList retainAll() method with Examples . See more Java LinkedList Example .

Leave a Reply

Your email address will not be published. Required fields are marked *

78 − = 71