Suppose I have a set with elements. How to create List of the same elements? I see methiods asSequence
and asIterable
, but no asList
, why?
To add a single element to a list or a set, use the add() function. The specified object is appended to the end of the collection. addAll() adds every element of the argument object to a list or a set. The argument can be an Iterable , a Sequence , or an Array .
To define a list of Strings in Kotlin, call listOf() function and pass all the Strings as arguments to it. listOf() function returns a read-only List. Since, we are passing strings for elements parameter, listOf() function returns a List<String> object.
To define a list of integers in Kotlin, call listOf() function and pass all the integers as arguments to it. listOf() function returns a read-only List. Since, we are passing integers for elements parameter, listOf() function returns a List<Int> object.
The function you're looking for is called toList()
:
val set: Set<Int> = setOf(1,2,3)
val list: List<Int> = set.toList()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With