Kotlin List subtract()
Syntax & Examples


Syntax of List.subtract()

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

infix fun <T> Iterable<T>.subtract( other: Iterable<T> ): Set<T>

This subtract() extension function of List returns a set containing all elements that are contained by this collection and not contained by the specified collection.



✐ Examples

1 Example

In this example,

  • We create a list of integers named list1 with elements 1, 2, 3, 4, 5.
  • We also create another list of integers named list2 with elements 3, 4, 5, 6, 7.
  • We use the subtract function to subtract list2 from list1, which returns a set of elements not present in list2.
  • The result is stored in result.
  • We print result using println().

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf(1, 2, 3, 4, 5)
    val list2 = listOf(3, 4, 5, 6, 7)
    val result = list1.subtract(list2)
    println(result)
}

Output

[1, 2]

2 Example

In this example,

  • We create a list of characters named list1 with elements 'a', 'b', 'c', 'd'.
  • We also create another list of characters named list2 with elements 'c', 'd', 'e', 'f'.
  • We use the subtract function to subtract list2 from list1, which returns a set of characters not present in list2.
  • The result is stored in result.
  • We print result using println().

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf('a', 'b', 'c', 'd')
    val list2 = listOf('c', 'd', 'e', 'f')
    val result = list1.subtract(list2)
    println(result)
}

Output

[a, b]

3 Example

In this example,

  • We create a list of strings named list1 with elements "apple", "banana", "cherry", "date".
  • We also create another list of strings named list2 with elements "banana", "cherry", "fig".
  • We use the subtract function to subtract list2 from list1, which returns a set of strings not present in list2.
  • The result is stored in result.
  • We print result using println().

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf("apple", "banana", "cherry", "date")
    val list2 = listOf("banana", "cherry", "fig")
    val result = list1.subtract(list2)
    println(result)
}

Output

[apple, date]

Summary

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