How to use HashSet.retainAll method in Kotlin
Overview
The retainAll method removes all the elements of the HashSet object that are not present in the passed Collection.
Syntax
fun retainAll(elements: Collection<E>): Boolean
Parameters
This method takes the collection object to be retained in the set as a parameter.
Return value
This method 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 example
The code below demonstrates how to use the retainAll method:
fun main() {//create a new HashSet which can have integer type as elementsvar set: HashSet<Int> = hashSetOf<Int>()// add three entriesset.add(1)set.add(2)set.add(3)println("\nThe set is : $set")val list = listOf(1,4);println("\nThe list is : $list")println("set.retainAll(list) : " + set.retainAll(list));println("The set is : $set")}
Code explanation
-
Line 3: We create a new
HashSetobject with the nameset. We use thehashSetOf()method to create an emptyHashSet. -
Line 6–8: We add three new elements
(1, 2, 3)to thesetusing theadd()method. -
Line 13: We create a new
Listobject withlistwith two elements[1,2]using thelistOfmethod. -
Line 14: We ise 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,3The
retainAllmethod 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
setwill be[1].
-