How to use the ArrayDeque.removeAll method in Kotlin

Overview

In Kotlin, the removeAll method removes all the elements of ArrayDeque contained in the passed Collection.

Syntax

The syntax of the method is given below:

fun removeAll(elements: Collection): Boolean

Arguments

This method takes a Collection of elements to be removed from this deque.

Return value

This method returns true if any one of the elements is removed from the deque. Otherwise, it returns false.

Code

The following code demonstrates the use of the removeAll method:

fun main() {
//create a new ArrayDeque which can have integer type as elements
var deque: ArrayDeque<Int> = ArrayDeque<Int>()
// add four entries
deque.add(1)
deque.add(2)
deque.add(3)
deque.add(4)
println("\nThe deque is : $deque")
val list1 = listOf(1,4);
println("\nThe list1 is : $list1")
// remove all the elements of list1 from deque
println("deque.removeAll(list1) : " + deque.removeAll(list1));
println("The deque is : $deque")
val list2 = listOf(5, 10);
println("\nThe list2 is : $list2")
// remove all the elements of list2 from deque
println("deque.removeAll(list2) : " + deque.removeAll(list2));
println("The deque is : $deque")
}

Explanation

  • Line 3: We create a new ArrayDeque object named deque.

  • Lines 6-9: We use the add() method to add four new elements (i.e., 1, 2, 3, and 4) to the deque.

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

  • Line 15: We use the removeAll method to remove all elements of the list1 present in the deque. In our case, the deque has some elements which will match the elements of list1. Those matched elements will be removed and true is returned.

* elements of deque is - [1,2,3,4]
* elements of list1 is - [1,4]

deque.removeAll(list1) - [2,3]
  • Line 17: We create a new List object named list2 with two elements, [5, 10], using the listOf method.

  • Line 19: We use the removeAll method to remove all elements of the list2 from the deque. In our case, no elements of list2 are present in the deque, so the deque remains unchanged, and false is returned.

* elements of deque - 2,3
* elements of list2 - 5,10

Elements of list2 are not present in the deque.

Free Resources