Kotlin Array - distinctBy() Function



The Kotlin array distinctBy() function is used to retrieve a list containing distinct elements using the selector function 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 or the same element in both capital and small letters in the given array, only the first occurrence will be present in the resulting list. For example, if the array is ['a', 'A', 'b', 'B'], then distinctBy will output [a, b].

Syntax

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

fun <T, K> Array<out T>.distinctBy(selector: (T) -> K): List<T>

Parameters

This function accepts selector as a parameter.

Return value

This function returns a list that contains only distinctBy element.

Example 1

Following is the basic example, we use distinctBy() function to select the elements from an array of strings whose distinction is based on the starting character −

fun main(args: Array<String>) {
   var array = arrayOf("apple", "banana", "mango", "berry", "mantos", "guava")
   var result = array.distinctBy { it[0] }
   println(result)
}

Output

Following is the output −

[apple, banana, mango, guava]

Example 2

Now, let's see another example, we select elements from an array of character whose distinction is based upon both lower and upper case −

fun main(args: Array<String>) {
   val char = arrayOf('a', 'A', 'b', 'B', 'A', 'a', 'b')
   
   //here distinct is not checking the upper and lower case.
   val res1 = char.distinct()
   println("use of distinct function $res1")
   
   //here distinctBy is checking the upper and lower case both
   val res2 = char.distinctBy { it.uppercase() }
   println("use of distinctBy function $res2")
}

Output

Following is the output −

use of distinct function [a, A, b, B]
use of distinctBy function [a, b]

Example 3

The example below calculates sum of the distinct element on an array −

fun main(){
    var sum:Int =0
    var add = arrayOf<Int>(1,2,3,1,2).distinctBy { it }
    for (i in 0 until  add.size){
       sum = sum + add[i]
    }
    println("sum of all distinct element is: $sum")
}

Output

Following is the output −

sum of all distinct element is: 6
kotlin_arrays.htm
Advertisements