Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a new list from another in Kotlin?

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()?

like image 362
Toni Joe Avatar asked Aug 23 '17 11:08

Toni Joe


People also ask

How do I copy a list into another list in Kotlin?

Kotlin has a standard function called ArrayList() that can be used to copy one array into another.

How do I add elements from one list to another in Kotlin?

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 in Kotlin?

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.

How do I get data from a list in Kotlin?

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.


1 Answers

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()
like image 110
hotkey Avatar answered Sep 18 '22 12:09

hotkey