What is the ArrayList.retainAll() 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 that uses a dynamic resizable array as the backing storage.
The retainAll() method
The ArrayList class contains the retainAll() method, which retains only the elements which are present in the specified input collection and removes all other elements from the array list.
Syntax
fun retainAll(elements: Collection<E>): Boolean
Arguments
- This method takes a collection of elements as input.
Return value
- This method returns
trueif any of the element is removed in the operation orfalseif the array list is not modified.
Things to note
-
ArrayListfollows the sequence of insertion of elements. -
It is allowed to contain duplicate elements.
The illustration below shows the function of the retainAll() method.
fun main(args : Array<String>) {val fruitList = ArrayList<String>()fruitList.add("Orange")fruitList.add("Apple")fruitList.add("Grapes")fruitList.add("Banana")println("Printing ArrayList elements --")println(fruitList)var retainList = ArrayList<String>()retainList.add("Apple")retainList.add("Grapes")fruitList.retainAll(retainList)println("Printing ArrayList elements after calling retainAll() --")println(fruitList)}
Explanation
-
First, we create an empty array list named
fruitListto store the strings. -
Next, we add a few fruit names to the
ArrayListobject using theadd()method, such as:"Orange","Apple","Grapes", and"Banana". -
Next, we create a new list
retainListand add two fruit names:"Apple"and"Grapes", using theadd()method. -
Next, we call the
retainAll()method by passingretainListas input. It removes all elements of the array list except the elements present in theretainList. -
The
Arraylistelements and result of theretainAll()method are displayed using theprint()function of thekotlin.iopackage.