Kotlin mutable list to array

Add new items to Array in Kotlin

In this post, we are going to describe different methods that can be used to add items to an array using Kotlin. We will be converting our arrays to mutable type to add new item.

fun main() < var names = arrayOf("James", "Walter", "Roy", "Salve") val namesList = names.toMutableList() namesList.add("Rick") namesList.add("Carol") names = namesList.toTypedArray() println(names.contentToString()) >
[James, Walter, Roy, Salve, Rick, Carol]

In the above code snippet,

  1. We have declared an array called names. We want to add new items to this array.
  2. We are converting the array to a mutable list using the toMutableList() function and adding the item to this mutable list using add() function.
  3. After adding the item we are converting the mutable list to an array using the toTypedArray() function.

Use ArrayList() and add items

You can use ArrayList in place of arrayof() while creating the function. When using an ArrayList, we can use its add() function to add an item to this array list. We can also iterate over the Array list using Kotlin For loop.

fun main() < val arr = ArrayList() arr.add("Nick") arr.add("John") arr.add("Rick") print(arr) >

Loop through ArrayList()

fun main() < val arr = ArrayList() arr.add("Nick") arr.add("John") arr.add("Rick") for (item in arr) < println(item) >>

Use Arrays.copyOf() to add an item to array

We can use Arrays.copyOf() function to add a new element to the array in Kotlin. The copyOf() function will create a copy of the array with the additional item on the last. Then we are replacing that item with our new item value.

fun addItemToArr(inputArr: Array, item: T): Array  < val result = inputArr.copyOf(inputArr.size + 1) result[inputArr.size] = item return result >fun main() < var nums = arrayOf(10, 20, 30, 40) nums = addItemToArr(nums, 50) println("Final array elements are:") for (item in nums) < print(item.toString() + " ") >>
Final array elements are: 10 20 30 40 50 

Create a mutable list and add items to it

val fruits = mutableListOf("Apple", "Banana", "Orange") fruits.add("Mango") println(fruits) // -> [Apple, Banana, Orange, Mango]

You can also create a mutable list and add items to it. The mutable list has a function add() where we can pass our item and it will be added to the list. The mutable list is also iterable.

Читайте также:  Html include local html file

Источник

MutableList

A generic ordered collection of elements that supports adding and removing elements.

Parameters

E — the type of elements contained in the list. The mutable list is invariant in its element type.

Functions

add

Adds the specified element to the end of this list.

Inserts an element into the list at the specified index.

addAll

Adds all of the elements of the specified collection to the end of this list.

Inserts all of the elements of the specified collection elements into this list at the specified index.

clear

Removes all elements from this collection.

listIterator

Returns a list iterator over the elements in this list (in proper sequence).

Returns a list iterator over the elements in this list (in proper sequence), starting at the specified index.

remove

Removes a single instance of the specified element from this collection, if it is present.

removeAll

Removes all of this collection’s elements that are also contained in the specified collection.

removeAt

Removes an element at the specified index from the list.

retainAll

Retains only the elements in this collection that are contained in the specified collection.

set

Replaces the element at the specified position in this list with the specified element.

subList

Returns a view of the portion of this list between the specified fromIndex (inclusive) and toIndex (exclusive). The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa.

Extension Properties

indices

Returns an IntRange of the valid indices for this collection.

lastIndex

Returns the index of the last item in the list or -1 if the list is empty.

Читайте также:  Php не пишутся логи

Extension Functions

addAll

Adds all elements of the given elements collection to this MutableCollection.

Adds all elements of the given elements sequence to this MutableCollection.

Adds all elements of the given elements array to this MutableCollection.

all

Returns true if all elements match the given predicate.

any

Returns true if collection has at least one element.

Returns true if at least one element matches the given predicate.

asIterable

Returns this collection as an Iterable.

asReversed

Returns a reversed mutable view of the original mutable List. All changes made in the original list will be reflected in the reversed one and vice versa.

asSequence

Creates a Sequence instance that wraps the original collection returning its elements when being iterated.

associate

Returns a Map containing key-value pairs provided by transform function applied to elements of the given collection.

associateBy

Returns a Map containing the elements from the given collection indexed by the key returned from keySelector function applied to each element.

Returns a Map containing the values provided by valueTransform and indexed by keySelector functions applied to elements of the given collection.

associateByTo

Populates and returns the destination mutable map with key-value pairs, where key is provided by the keySelector function applied to each element of the given collection and value is the element itself.

Populates and returns the destination mutable map with key-value pairs, where key is provided by the keySelector function and and value is provided by the valueTransform function applied to elements of the given collection.

fun < T , K , V , M : MutableMap < in K , in V >> Iterable < T >. associateByTo (
destination : M ,
keySelector : ( T ) -> K ,
valueTransform : ( T ) -> V
) : M

Читайте также:  Bitrix env обновить php

associateTo

Populates and returns the destination mutable map with key-value pairs provided by transform function applied to each element of the given collection.

associateWith

Returns a Map where keys are elements from the given collection and values are produced by the valueSelector function applied to each element.

associateWithTo

Populates and returns the destination mutable map with key-value pairs for each element of the given collection, where key is the element itself and value is provided by the valueSelector function applied to that key.

binarySearch

Searches this list or its range for the provided element using the binary search algorithm. The list is expected to be sorted into ascending order according to the specified comparator, otherwise the result is undefined.

fun < T > List < T >. binarySearch (
element : T ,
comparator : Comparator < in T >,
fromIndex : Int = 0 ,
toIndex : Int = size
) : Int

Searches this list or its range for an element for which the given comparison function returns zero using the binary search algorithm.

fun < T > List < T >. binarySearch (
fromIndex : Int = 0 ,
toIndex : Int = size ,
comparison : ( T ) -> Int
) : Int

binarySearchBy

Searches this list or its range for an element having the key returned by the specified selector function equal to the provided key value using the binary search algorithm. The list is expected to be sorted into ascending order according to the Comparable natural ordering of keys of its elements. otherwise the result is undefined.

fun < T , K : Comparable < K >> List < T >. binarySearchBy (
key : K ? ,
fromIndex : Int = 0 ,
toIndex : Int = size ,
selector : ( T ) -> K ?
) : Int

chunked

Splits this collection into a list of lists each not exceeding the given size.

Splits this collection into several lists each not exceeding the given size and applies the given transform function to an each.

Источник

Оцените статью