Kotlin List distinct()
Syntax & Examples
Syntax of List.distinct()
The syntax of List.distinct() extension function is:
fun <T> Iterable<T>.distinct(): List<T>
This distinct() extension function of List returns a list containing only distinct elements from the given collection.
✐ Examples
1 Example
In this example,
- We create a list named
list1
containing the characters'a', 'p', 'p', 'l', 'e'
. - We apply the
distinct()
function tolist1
to get a new listdistinctList
containing only unique elements. - The resulting list
distinctList
contains elements'a', 'p', 'l', 'e'
, as duplicates are removed. - Finally, we print the
distinctList
to standard output using print statement.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf("a", "p", "p", "l", "e");
val distinctList = list1.distinct();
print(distinctList);
}
Output
[a, p, l, e]
2 Example
In this example,
- We create a list named
list1
containing the integers10, 20, 30, 10, 20
. - We apply the
distinct()
function tolist1
to get a new listdistinctList
containing only unique elements. - The resulting list
distinctList
contains elements10, 20, 30
, with duplicates removed. - Finally, we print the
distinctList
to standard output using print statement.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf(10, 20, 30, 10, 20);
val distinctList = list1.distinct();
print(distinctList);
}
Output
[10, 20, 30]
3 Example
In this example,
- We create a list named
list1
containing the strings'apple', 'banana', 'mango', 'apple', 'banana'
. - We apply the
distinct()
function tolist1
to get a new listdistinctList
containing only unique elements. - The resulting list
distinctList
contains elements'apple', 'banana', 'mango'
, with duplicates removed. - Finally, we print the
distinctList
to standard output using print statement.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf("apple", "banana", "mango", "apple", "banana");
val distinctList = list1.distinct();
print(distinctList);
}
Output
[apple, banana, mango]
Summary
In this Kotlin tutorial, we learned about distinct() extension function of List: the syntax and few working examples with output and detailed explanation for each example.