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 elementsvar deque: ArrayDeque<Int> = ArrayDeque<Int>()// add three entriesdeque.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
ArrayDequeobject with the namedeque. -
Lines 6 to 8: We add three new elements(
1,2,3) to thedequeusing theadd()method. -
Line 13: We create a new
Listobject withlistwith 2 elements[1,2]using thelistOfmethod. -
Line 14: We use the
retainAllmethod to retain only elements that are present in thelist. In our case, the elements of thelistanddequeare as follows:
Elements of list -- 1,4
Elements of deque -- 1,2,3
The retainAll method will check:
-
If element
1ofdequeis present in thelist. Thelistcontains1, so1is retained in thedeque. -
If element
2ofdequeis present in thelist. Thelistdoesn’t contain2, so2is removed from thedeque. -
If element
3ofdequeis present in thelist. Thelistdoesn’t contain3, so3is removed from thedeque.
The resulting deque is [1].