Kotlin List toHashSet()
Syntax & Examples
Syntax of List.toHashSet()
The syntax of List.toHashSet() extension function is:
fun <T> Iterable<T>.toHashSet(): HashSet<T>This toHashSet() extension function of List returns a new HashSet of all elements.
✐ Examples
1 Example
In this example,
- We create a list named
listcontaining integers and some duplicate elements. - We call the
toHashSet()function onlist. - The resulting HashSet, which contains unique elements, is stored in
set. - Finally, we print the HashSet to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(1, 2, 3, 4, 5, 5, 4, 3, 2, 1);
val set = list.toHashSet();
println(set);
}Output
[1, 2, 3, 4, 5]
2 Example
In this example,
- We create a list named
listcontaining characters and some duplicate elements. - We call the
toHashSet()function onlist. - The resulting HashSet, which contains unique elements, is stored in
set. - Finally, we print the HashSet to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf('a', 'b', 'c', 'c', 'b', 'a');
val set = list.toHashSet();
println(set);
}Output
[a, b, c]
3 Example
In this example,
- We create a list named
listcontaining strings and some duplicate elements. - We call the
toHashSet()function onlist. - The resulting HashSet, which contains unique elements, is stored in
set. - Finally, we print the HashSet to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "apple", "banana");
val set = list.toHashSet();
println(set);
}Output
[banana, apple]
Summary
In this Kotlin tutorial, we learned about toHashSet() extension function of List: the syntax and few working examples with output and detailed explanation for each example.