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 LinkedHashSet is similar to the HashSet, except that LinkedHashSet maintains the insertion order of elements, whereas HashSet does not. Read more about LinkedHashSet here.

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 LinkedHashSet and ArrayList class.

  • Lines 5 to 8: Create a new LinkedHashSet object with the name set and use the add method to add three elements (1,2,3) to the set object.

  • Lines 9 to 11: Create a new ArrayList object with the name list and use the add method to add two elements (1,4) to the list object.

  • In line 15: Use the retainAll method to retain only elements that are present in the list. In our case, the elements of the list and set are as follows:

Elements of list -- 1,4
Elements of set -- 1,2,3

The retainAll method will:

  • Check if element 1 of set is present in the list. The list contains 1, so 1 is retained in the set.

  • Check if element 2 of set is present in the list. The list doesn’t contain 2, so 2 is removed from the set.

  • Check if element 3 of set is present in the list. The list doesn’t contain 3, so 3 is removed from the set.

The resulting set will be [1].

Free Resources