What is the LinkedHashSet.retainAll method in Java?
The retainAll method removes all the elements of the LinkedHashSet object that are not present in the passed collection.
The
LinkedHashSetis similar to theHashSet, except thatLinkedHashSetmaintains the insertion order of elements, whereasHashSetdoes not. Read more aboutLinkedHashSethere.
Syntax
boolean retainAll(Collection<?> c)
Parameters
This method takes the collection object to be retained in the set as a parameter.
Return value
retainAll() returns true if the set changes as a result of the call (any element is removed from the set because the element is not present in the collection). Otherwise, the method returns false.
Code
import java.util.LinkedHashSet;import java.util.ArrayList;class RetainAll {public static void main( String args[] ) {LinkedHashSet<Integer> set = new LinkedHashSet<>();set.add(1);set.add(2);set.add(3);ArrayList<Integer> list = new ArrayList<>();list.add(1);list.add(4);System.out.println("The set is "+ set);System.out.println("The list is "+ list);System.out.println("\nCalling set.retainAll(list). Is set changed - " + set.retainAll(list));System.out.println("\nThe set is "+ set);}}
Explanation
In the code above:
-
In lines 1 and 2: Import the
LinkedHashSetandArrayListclass. -
Lines 5 to 8: Create a new
LinkedHashSetobject with the namesetand use theaddmethod to add three elements (1,2,3) to thesetobject. -
Lines 9 to 11: Create a new
ArrayListobject with the namelistand use theaddmethod to add two elements (1,4) to thelistobject. -
In line 15: Use the
retainAllmethod to retain only elements that are present in thelist. In our case, the elements of thelistand set are as follows:
Elements of list -- 1,4
Elements of set -- 1,2,3
The retainAll method will:
-
Check if element
1ofsetis present in thelist. Thelistcontains1, so1is retained in theset. -
Check if element
2ofsetis present in thelist. Thelistdoesn’t contain2, so2is removed from theset. -
Check if element
3ofsetis present in thelist. Thelistdoesn’t contain3, so3is removed from theset.
The resulting set will be [1].