Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

kotlin
communitycreator

How to use HashSet.retainAll method in Kotlin

Programming Bytes

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 elements
  var set: HashSet<Int> = hashSetOf<Int>()

  // add three entries
  set.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")

}
Using the retainAll method

Code explanation

  • Line 3: We create a new HashSet object with the name set. We use the hashSetOf() method to create an empty HashSet.

  • Line 6–8: We add three new elements (1, 2, 3) to the set using the add() method.

  • Line 13: We create a new List object with list with two elements [1,2] using the listOf method.

  • Line 14: We ise 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].

RELATED TAGS

kotlin
communitycreator
RELATED COURSES

View all Courses

Keep Exploring