How to use ArrayDeque.retainAll method in Kotlin

Overview

The retainAll method removes all the elements of the ArrayDeque 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 deque as a parameter.

Return value

This method returns true if the deque changes as a result of the call (any element is removed from the deque because the element is not present in the collection). Otherwise, the method returns false.

Code

The below code demonstrates how to use the retainAll method:

fun main() {
//create a new ArrayDeque which can have integer type as elements
var deque: ArrayDeque<Int> = ArrayDeque<Int>()
// add three entries
deque.add(1)
deque.add(2)
deque.add(3)
println("\nThe deque is : $deque")
val list = listOf(1,4);
println("\nThe list is : $list")
println("deque.retainAll(list) : " + deque.retainAll(list));
println("The deque is : $deque")
}

Explanation

In the above code, we see the following:

  • Line 3: We create a new ArrayDeque object with the name deque.

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

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

  • Line 14: We use the retainAll method to retain only elements that are present in the list. In our case, the elements of the list and deque are as follows:

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

The retainAll method will check:

  • If element 1 of deque is present in the list. The list contains 1, so 1 is retained in the deque.

  • If element 2 of deque is present in the list. The list doesn’t contain 2, so 2 is removed from the deque.

  • If element 3 of deque is present in the list. The list doesn’t contain 3, so 3 is removed from the deque.

The resulting deque is [1].

Free Resources