Kotlin Array - distinct() Function



The Kotlin array distinct() function is used to retrieve a list containing only distinct elements from the given array. The elements in the resulting list are in the same order as they were in the source array.

If there are multiple similar elements in the given array, only the first one will be present in the resulting list.

Syntax

Following is the syntax of Kotlin array distinct() function −

fun <T> Array<out T>.distinct(): List<T>

Parameters

This function does not accepts any parameter.

Return value

This function returns a list that contains only distinct element.

Example 1

Following is the basic example to demonstrate the use of distinct() function −

fun main(args: Array<String>) {
   val numbers = arrayOf(1, 3, 5, 7, 9, 7, 3)
   val list = numbers.distinct()
   println("Distinct element of an array: $list")
}

Output

Following is the output −

Distinct element of an array: [1, 3, 5, 7, 9]

Example 2

Now, let's see another example to create, manipulate, and print arrays, and also to remove duplicate elements from an array using distinct() function −

fun main(args: Array<String>) {
   var array = Array(10) { i ->
      if(i<3) {'A'}
      else if(i<5) {"tutorix"}
      else {5}
   }

   var result=array.distinct()
   print("The distinct elements in the array are: \n")
   for (i in 0..result.size-1) {
      println("result[$i] = ${result[i]} ")
   }
}

Output

Following is the output −

The distinct elements in the array are: 
result[0] = A 
result[1] = tutorix 
result[2] = 5

Example 3

The example below creates an array that stores random element including repeated one. We then use the distinct() function to display only the distinct element −

fun main(args: Array<String>) {
   var array = Array(8) { i ->
      if(i<3) {'c'}
      else if(i<5) {"Hi"}
      else {3}
   }

   print("The elements in the array are: \n")
   for (i in 0..array.size-1) {
      println("array[$i] = ${array[i]} ")
   }

   var result=array.distinct()    
   println("Distinct element of an array: $result ")    
}

Output

Following is the output −

The elements in the array are: 
array[0] = c 
array[1] = c 
array[2] = c 
array[3] = Hi 
array[4] = Hi 
array[5] = 3 
array[6] = 3 
array[7] = 3 
Distinct element of an array: [c, Hi, 3] 
kotlin_arrays.htm
Advertisements