What is the ArrayList.removeAll() method in Kotlin?

The kotlin.collections package is part of Kotlin’s standard library, and it contains all collection types, such as map, list, set, etc.

The package provides the ArrayList class, which is a mutable list and uses a dynamic, resizable array as backing storage.

The removeAll() method

The ArrayList class contains the removeAll() method which removes all the elements present in the specified input collection from the array list.

Syntax

fun removeAll(elements: Collection<E>): Boolean

Arguments

  • This method takes a collection of elements as input.

Return value

  • It returns true if any of the elements from the specified collection are removed and false if the array list is not modified.

The illustration below shows the function of the removeAll() method:

Removing a collection of elements from an array list using removeAll() method

Example

fun main(args : Array<String>) {
val monthList = ArrayList<String>()
monthList.add("January")
monthList.add("February")
monthList.add("March")
monthList.add("April")
monthList.add("May")
println("Printing ArrayList elements --")
println(monthList)
val oddMonths = ArrayList<String>()
oddMonths.add("March")
oddMonths.add("May")
monthList.removeAll(oddMonths)
println("Printing ArrayList elements after calling removeAll() --")
println(monthList)
}

Explanation

  • Line 2: We create an empty array list named monthList to store the strings.

  • Lines 4-8: We add a few months’ names to the monthList object using the add() method.

  • Lines 12-14: We create another collection oddMonths containing the name of a few months to be deleted.

  • Line 16: We call the removeAll() method and pass the collection oddMonths created above as input. It removes all the elements of the input collection that are present in the array list.

  • Line 18: We print the elements of monthList after removing oddMonths.

The ArrayList elements before and after calling removeAll() method are displayed using the println() function of the kotlin.io package.

Free Resources