What is the ArrayList.containsAll() method in Kotlin?
Overview
The kotlin.collections package is part of Kotlin’s standard library and 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 the backing storage.
The containsAll() method
The ArrayList class contains the containsAll() method, which checks for the presence of all elements of the specified input collection in the array list.
Syntax
fun containsAll(elements: Collection<E>): Boolean
Parameters
The containsAll() method takes the collection of elements to search as input.
Return value
containsAll() returns true if all the elements of the input collection are present in the array list, and false otherwise.
Things to note
-
ArrayListfollows the sequence of insertion of elements. -
ArrayListis allowed to contain duplicate elements.
The illustration below shows the function of the containsAll() method.
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 inputList = ArrayList<String>()inputList.add("January")inputList.add("February")println("Printing Input collection elements--")println(inputList)val result = monthList.containsAll(inputList)println("Is input list present in the array list? : ${result}")}
Explanation
-
Line 2: We create an empty array list named
monthListto store the strings. -
Line 4 to 8: We use the
add()method to add a few month names to theArrayListobject, such as"January","February","March","April", and"May". -
Line 12 to 14: We create a new array list
inputListand add month names"January"and"February"to it. -
Line 17: We call the
containsAll()method and pass theinputListcollection as the parameter. ThecontainsAll()method returnstrue, as all elements of the input collection are present in the array list.
We use the println() function of the kotlin.io package to display the Arraylist elements and result of the containsAll() method.