In Java we can create a new list from another like this:
List<Integer> list1 = new ArrayList<>();
list1.add(1)
list1.add(-10)
list1.add(12)
list1.add(37)
List<Integer> list2 = new ArrayList<>(list1);
how can we achieve the same result as above in Kotlin using listOf()
or mutableListOf()?
Kotlin has a standard function called ArrayList() that can be used to copy one array into another.
Adding elements 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 .
How do I make a string list with Kotlin? 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 get the element from a List in Kotlin present at specific index, call get() function on this list and pass the index as argument to get() function. The Kotlin List. get() function returns the element at the specified index in this list.
You can use .toList()
and .toMutableList()
extensions to copy a container (an array, a collection, a sequence) into a new list:
val list1 = listOf(1, -10, 12, 37)
val list2 = list1.toList()
val mutableList2 = list2.toMutableList()
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