Kotlin Training Program

DOWNLOAD APP

FEEDBACK

ArrayLists

ArrayList data structure is used to store multiple items of same data type in a linear fashion.

Features

Dynamic sizing

In contrast to Arrays, Lists (ArrayLists) size is dynamic. It increases it size automatically as we add more and more elements.

💡 Wondering How?
Well, it is an array internally & has some predefined size initially. While adding elements if it is about to fill up, its size gets doubled to accomodate more elements!

By-default immutable

ArrayLists once created are by-default immuatble i.e. items can not be added or removed. If we want to do so, we use MutableList.

Operations

Creating List

Following are the ways in which you can create a new list :

  1. Create an empty list using emptyList / listOf / mutableListOf function :

     emptyList</* Type */>() // Creates immutable list
    // OR
    listOf</* Type */>() // Creates immutable list
    // OR
    mutableListOf</* Type */>() // Creates mutable list
     

    Example :

     fun main() {
        val nums = emptyList<Int>()
        val chars = emptyList<Char>()
    }
     
  2. Create a list prefilled with some elements :

     listOf(/* Elements */) // Creates immutable list
    // OR
    mutableListOf(/* Elements */) // Creates mutable list
     

    Example :

     fun main() {
        val nums = listOf(2, 3, 5, 7, 11)
        val nums1 = mutableListOf(2, 3, 5, 7, 11)
    }
     
  3. Create a list using List constructor & generating initial elements :

     List(/* Size */) { /* Element Builder */ }
     

    Example :

     fun main() {
        val nums = List(5) { it } // [0, 1, 2, 3, 4]
        val doubles = List(5) { it*2 } // [0, 2, 4, 6, 8]
        val squares = List(5) { it*it } // [0, 1, 4, 9, 16]
    }
     
  4. Create a list using IntRange :

     /* range */.toList() // Creates immutable list
    // OR
    /* range */.toMutableList() // Creates mutable list
     

    Example :

     fun main() {
        val nums = (1 .. 5).toList() // [1, 2, 3, 4, 5]
        val nums1 = (100 downTo 0 step 10).toList() // [100, 90, 80, ... , 0]
    }
     

Printing List

Unlike Arrays, we need not loop over the List to print all its elements. Printing the List variable will automatically print all its elements :

 fun main() {
    val nums = (100 downTo 0 step 10).toList()
    println(nums)
}

// Output : [100, 90, 80, 70, 60, 50, 40, 30, 20, 10, 0]
 

💡 Wondering How?
Recall that all classes implicitly inherit from the Any class and List class is no exception. List class already has overriden the Any.toString() to print all elements using loop so we don’t have to!

Alternatively, if we want to print the elements in some other way, we can use for loop, forEach or forEachIndexed function also.

Check existence of an Element

To check whether an element is present in the List, we can use the contains() function :

 list.contains(/* Element */)
 

Example :

 fun main() {
    val nums = listOf(1, 2, 3)
    println("contains(1) = ${nums.contains(1)}")
    println("contains(4) = ${nums.contains(4)}")
}

/* Output :
contains(1) = true
contains(4) = false
*/
 

Element Access

Like for Arrays, we can access List elements using either indexing operator or the get() function :

 list[/* index */]
// OR
list.get(/* index */)
 

Example :

 fun main() {
    val nums = listOf(2, 3, 5, 7, 11)
    println(nums[2]) // Prints 5
    println(nums.get(1)) // Prints 3
}
 

Modify List

Note that modifying elements of List is not allowed because it is immutable. However, for a MutableList we can perform the following operations :

Update elements

For updating element at a particular index, we can either use the indexing operator or the set() function :

 list[/* index */] = /* new value */
// OR
list.set(/* index */, /* new value */)
 

Example :

 fun main() {
    val nums = mutableListOf(2, 3, 5, 7, 11)

    // Double the 1st element
    nums[0] *= 2
    // OR
    nums.set(0, nums[0] * 2)

    println("nums[0] = ${nums[0]}") // Prints 4
}
 

Removing elements

By element (single instance, same list)

We can remove an element from the list using the remove() function :

 list.remove(/* element */)
 

Example :

 fun main() {
    val nums = mutableListOf(1, 2, 3, 4, 5, 2)
    println("removed 2: ${nums.remove(2)}")
    println("removed 3: ${nums.remove(3)}")
    println("removed 6: ${nums.remove(6)}")
    println("updated list = $nums")
}

/* Output :
removed 2: true
removed 3: true
removed 6: false
updated list = [1, 4, 5, 2] */
 

Note :

  • remove() function returns a Boolean indicating whether the item was found & removed or not. In the above example, 6 was not found so it returned false.
  • remove() function removes only the first occurence of the passed element. In the above example, 2nd occurence of 2 is not removed.

By element (single instance, new list)

We can remove an element from the list using the subtraction operator -. But it returns a new list and original list remains unmodified.

 list - /* element */
 

Example :

 fun main() {
    val nums = mutableListOf(0, 1, 2)
    val newNums = nums - 0
    println("nums = $nums")
    println("newNums = $newNums")
}

/* Output :
nums = [0, 1, 2]
newNums = [1, 2] */
 

Note :

  • Even though nums is a MutableList, the new list returned by - operation is a List and not MutableList.
  • - operator can also be used with normal Lists as it does not modify original list.

By index

We can remove the element at a specified index from the list using the removeAt() function :

 list.removeAt(/* index */)
 

Example :

 fun main() {
    val nums = mutableListOf(1, 2, 4, 3, 5, 2)
    println("removed nums[2] = ${nums.removeAt(2)}")
    println("removed nums[1] = ${nums.removeAt(1)}")
    println("updated list = $nums")
}

/* Output :
removed nums[2] = 4
removed nums[1] = 2
updated list = [1, 3, 5, 2] */
 

Note :

  • removeAt() function returns the element at specified index (if found) otherwise throws IndexOutOfBoundsException (if not found).

By predicate

To remove multiple elements from the list that match a given predicate / condition, we can use the removeIf function :

 list.removeIf { /* predicate */ }
 

Example :

 fun main() {
    val nums = mutableListOf(-2, -1, 0, 1, 2, 2, 2)
    nums.removeIf { it == 2 } // Removes all 2s
    nums.removeIf { it < 0 }  // Removes all -ive nums
    println("updated list = $nums")
}

// Output : updated list = [0, 1]
 

From another list

We can remove all elements of one list from another using the removeAll() function :

 list.removeAll(/* list of items to remove */)
 

Example :

 fun main() {
    val nums = mutableListOf(1, 2, 3, 4, 5)
    val numsToRemove = listOf(2, 3)
    nums.removeAll(numsToRemove)
    println("nums = $nums")
}

// Output : nums = [1, 4, 5]
 

Note:

  • removeAll() function returns a Boolean specifying whether at least one of the element was removed.
  • We can also use the - operator here but it will create a new list instead of removing from the original list.

Adding elements

At the end (same list)

We can add a new element to a list using the add() function :

 list.add(/* element */)
 

Example :

 fun main() {
    val nums = mutableListOf(0, 1, 2)
    nums.add(3)
    println("nums = $nums")
}

// Output : nums = [0, 1, 2, 3]
 

At the end (new list)

We can add a new element to a list using the + operator, but it creates a new list and original list remains unmodified :

 list + /* element */
 

Example :

 fun main() {
    val nums = mutableListOf(0, 1, 2)
    val newNums = nums + 3
    println("nums = $nums")
    println("newNums = $newNums")
}

/* Output :
nums = [0, 1, 2]
newNums = [0, 1, 2, 3] */
 

At a particular index

We can add a new element at a specified index in a list using the add() function :

 add(/* index */, /* element */)
 

Example :

 fun main() {
    val nums = mutableListOf(0, 1, 2)
    nums.add(0, 3) // Adds 3 at index 0
    println("nums = $nums")
}

// Output : nums = [3, 0, 1, 2]
 

From another list

We can add all elements of one list from another using the addAll() function :

 list.addAll(/* list of items to add */)
 

Example :

 fun main() {
    val nums = mutableListOf(1, 2, 3)
    val numsToAdd = listOf(4, 5)
    nums.addAll(numsToAdd)
    println("nums = $nums")
}

// Output : nums = [1, 2, 3, 4, 5]
 

Note :

  • We can also use the + operator here but it will create a new list instead of adding to the original list.