Kotlin List minus()
Syntax & Examples
Syntax of List.minus()
There are 4 variations for the syntax of List.minus() extension function. They are:
operator fun <T> Iterable<T>.minus(element: T): List<T>
This extension function returns a list containing all elements of the original collection without the first occurrence of the given element.
operator fun <T> Iterable<T>.minus( elements: Array<out T> ): List<T>
This extension function returns a list containing all elements of the original collection except the elements contained in the given elements array.
operator fun <T> Iterable<T>.minus( elements: Iterable<T> ): List<T>
This extension function returns a list containing all elements of the original collection except the elements contained in the given elements collection.
operator fun <T> Iterable<T>.minus( elements: Sequence<T> ): List<T>
This extension function returns a list containing all elements of the original collection except the elements contained in the given elements sequence.
✐ Examples
1 Example
In this example,
- We create a list named
list1
containing the numbers[1, 2, 3, 4, 5]
. - We apply the
minus
function with the element3
to remove it from the list. - The resulting list, after removing the first occurrence of
3
, is stored inresult
. - Finally, we print the value of
result
to standard output using theprint
statement.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf(1, 2, 3, 4, 5);
val result = list1.minus(3);
print(result);
}
Output
[1, 2, 4, 5]
2 Example
In this example,
- We create a list named
list1
containing the characters['a', 'b', 'c', 'd', 'e']
. - We apply the
minus
function with an array containing elements'a'
,'c'
, and'e'
to remove them from the list. - The resulting list, after removing the specified elements, is stored in
result
. - Finally, we print the value of
result
to standard output using theprint
statement.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf('a', 'b', 'c', 'd', 'e');
val result = list1.minus(arrayOf('a', 'c', 'e'));
print(result);
}
Output
[b, d]
3 Example
In this example,
- We create a list named
list1
containing the strings['apple', 'banana', 'orange', 'grape']
. - We apply the
minus
function with another list containing elements'orange'
and'grape'
to remove them from the list. - The resulting list, after removing the specified elements, is stored in
result
. - Finally, we print the value of
result
to standard output using theprint
statement.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf("apple", "banana", "orange", "grape");
val result = list1.minus(listOf("orange", "grape"));
print(result);
}
Output
[apple, banana]
Summary
In this Kotlin tutorial, we learned about minus() extension function of List: the syntax and few working examples with output and detailed explanation for each example.