LinkedList boolean retainAll(Collection c) method Example Program


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

Program

package com.candidjava;

import java.util.ArrayList;
import java.util.LinkedList;

/* 
 * @author : Mohan 
 * @description : RetailAll program to retain only elements specified in the specified collection.
 * 
 */
public class LinkedListRetainAll {
	public static void main(String[] args) {
		LinkedList<String> ll = new LinkedList<String>();
		ll.add("hari");
		ll.add("mohan");
		ll.add("anand");
		ll.add("saravan");
		ll.add("sampath");
		ll.add("kumar");
		ArrayList<String> al = new ArrayList<String>();
		al.add("anand");
		al.add("sampath");
		al.add("ram");
		System.out.println("linkedlist" + ll);
		System.out.println("Arraylist" + al);
		ll.retainAll(al);
		al.retainAll(ll);
		System.out.println("linkedlist after using retainall" + ll);
		System.out.println("arraylist after using retainall" + al);
	}
}

Output

linkedlist[hari, mohan, anand, saravan, sampath, kumar]
Arraylist[anand, sampath, ram]
linkedlist after using retainall[anand, sampath]
arraylist after using retainall[anand, sampath]

Explanation

boolean retainAll(Collection<?> c)
Retains only the elements in this list that are contained in the specified collection (optional operation). In other words, removes from this list all of its elements that are not contained in the specified collection.

Specified by:
retainAll in interface Collection<E>

Parameters:
c - collection containing elements to be retained in this list

Returns:
true if this list changed as a result of the call

Throws:
UnsupportedOperationException - if the retainAll operation is not supported by this list
ClassCastException - if the class of an element of this list is incompatible with the specified collection (optional)
NullPointerException - if this list contains a null element and the specified collection does not permit null elements (optional), or if the specified collection is null

See Also:
remove(Object), contains(Object)


Related Post

Comments


©candidjava.com