The collection interface is the main interface that represents a collection of items. The collection interface is a member of the immutable type of list and therefore provides read-only functionalities. The collection interface inherits the Iterable interface and provides its own functions:
fun collectionInterface(){
val collectionValues : Collection <Int> = listOf(1,2,3,4,5)
val collectionIterator = collectionValues.iterator()
while (collectionIterator.hasNext()) {
print(collectionIterator.next())
}
}
Take a look at the following diagram, which shows the properties and functions that are provided by the collection interface:
The following is a list of the properties and functions of the collection interface:
- size: This property return the size of the collection.
- isEmpty(): This function returns true if the collection is empty. Otherwise, it returns false.
- contains(): This function returns true if the specified element is in the list. Otherwise, it returns false.
- containsAll(): This function returns true if a list is a subset of a collection. Otherwise, it returns false.
Take a look at the following example:
fun collectionFunctions(){
val collectionValues : Collection <Int> = listOf(1,2,3,4,5)
println("Size ${collectionValues.size}")
println("is collection empty: ${collectionValues.isEmpty()}")
println("collection contains element 3: ${collectionValues.contains(3)}")
var mini = listOf(2,3,4)
var answer = collectionValues.containsAll(mini)
println("Does collection contain mini collection: $answer")
}
The output of the preceding code is as follows:
Size 5
is collection empty: false
contains contains element 3: true
Collection contains mini collection true