Kotlin List minusElement()
Syntax & Examples


Syntax of List.minusElement()

The syntax of List.minusElement() extension function is:

fun <T> Iterable<T>.minusElement(element: T): List<T>

This minusElement() extension function of List returns a list containing all elements of the original collection without the first occurrence of the given element.



✐ Examples

1 Example

In this example,

  • We create a list of integers named list containing elements 1, 2, 3, 4, 5.
  • We use the minusElement() function to remove the first occurrence of 3 from the list.
  • The modified list, modifiedList, without the element 3 is printed to standard output using println statement.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(1, 2, 3, 4, 5)
    val modifiedList = list.minusElement(3)
    println(modifiedList)
}

Output

[1, 2, 4, 5]

2 Example

In this example,

  • We create a list of characters named list containing elements 'a', 'b', 'c', 'd'.
  • We use the minusElement() function to remove the first occurrence of 'c' from the list.
  • The modified list, modifiedList, without the element 'c' is printed to standard output using println statement.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf('a', 'b', 'c', 'd')
    val modifiedList = list.minusElement('c')
    println(modifiedList)
}

Output

[a, b, d]

3 Example

In this example,

  • We create a list of strings named list containing elements "apple", "banana", "cherry", "apple".
  • We use the minusElement() function to remove the first occurrence of "apple" from the list.
  • The modified list, modifiedList, without the element "apple" is printed to standard output using println statement.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf("apple", "banana", "cherry", "apple")
    val modifiedList = list.minusElement("apple")
    println(modifiedList)
}

Output

[banana, cherry, apple]

Summary

In this Kotlin tutorial, we learned about minusElement() extension function of List: the syntax and few working examples with output and detailed explanation for each example.