Lesson 46 – List and MutableList in Kotlin Programming Language

Lesson 46 – List and MutableList in Kotlin Programming Language

Hello viewer, You can now have our Tutorial Lessons in your android mobile device and read it offline.
Download kotlin Programming APP on PlayStore
Download Website SEO Lessons APP on PlayStore

A list is an ordered collection of data. An item can be retrieved by the position in the collection.

We can create in Kotlin both immutable and mutable lists.

Creation of an unchanging list.

Problem 1

Create an unchanging list with the days of the week. Test the main properties and methods for managing the list.

Project173 – Home.kt

fun main (args: Array <String>) {
    // www.coding180.com
    var list1: List <String> = listOf ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
    println ("Print the complete list")
    println (list1)
    println ("Print the first item in the list")
    println (list1 [0])
    println ("Print the first item in the list")
    println (list1.first ())
    println ("Print the last item in the list")
    println (list1.last ())
    println ("Print the last item in the list")
    println (list1 [list1.size-1])
    println ("Print the number of items in the list")
    println (list1.size)
    println ("Scroll through the complete list with a for")
    for (element in list1)
        print ("$element")
    println ()
    println ("Print the item and its position")
    for (position in list1.indices)
        print ("[$position] ${list1 [position]}")
}

To create an immutable list we can call the function listOf and pass as a parameter the data to be stored, we must indicate the type of data that it stores after List:

    Var list1: List <String> = listOf ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")

Once the list is created we can not modify your data:

    List1 [0] = "Sunday"

Nor can we add elements:

List1.add ("January")

What we can do with an immutable list is to access its elements, for example, to traverse it with a for:

    For (element in list1)
        Print ("$element")

Access any element by a subscript:

    Println ("Print the first item in the list")
    Println (list1 [0])

If we want to know all the properties and methods of List we can visit the documentation of the standard library of Kotlin.

Problem 2

Let’s see another example of creating an immutable list but using the List function to which we pass the size of the list and a lambda function indicating which values to store:

Project 174 

fun load (): Int {
    print ("Enter an integer:")
    val value = readLine () !!. toInt ()
    return value
}

fun main (args: Array <String>) {
    var list1: List <Int> = List (5, {load ()})
    println (list1)
}

In this example, we create an immutable list by calling the List function to which we pass in the first parameter the size of the list to create and the second parameter is the lambda function that will be executed for each element.

In the lambda function call to load but we could have coded in that place the load:

Fun main (args: Array <String>) {
    Var list1: List <Int> = List (5) {
        Print ("Enter an integer:")
        Val value = readLine () !!. ToInt ()
        value
    }
    Println (list1)
}

The value that returns the lambda function is the data that is stored in each component of the collection.

Creating a mutable list.

Problem 3

Create a mutable list with the ages of several people. Test the main properties and methods for managing the mutable list.

Project175

fun main (args: Array <String>) {
    // www.coding180.com
    val ages: MutableList <Int> = mutableListOf (23, 67, 12, 35, 12)
    println ("List of ages")
    println (ages)
    ages [0] = 60
    println ("Complete list after changing the first age")
    println (ages)
    println ("First age stored in list")
    println (ages [0])
    println ("Average age")
    println (ages.average ())
    println ("We add an age at the bottom of the list:")
    ages.add (50)
    println ("List of ages")
    println (ages)
    println ("We added an age at the top of the list:")
    ages.add (0, 17)
    println ("List of ages")
    println (ages)
    println ("We removed the first age from the list:")
    ages.removeAt (0)
    println ("List of ages")
    println (ages)
    print ("Number of persons of legal age:")
    val cont = ages.count {it >= 18}
    println (cont)
    ages.removeAll {it == 12}
    println ("List of ages after deleting those that are 12 years old")
    println (ages)
    ages.clear ()
    println ("List of ages after deleting the list completely")
    println (ages)
    if (ages.isEmpty ())
        println ("There are no ages in the list")
}

This example shows how to create a mutable list by calling the mutableListOf function and indicating the initial values:

    Val ages: MutableList <Int> = mutableListOf (23, 67, 12, 35, 12)

To add a new item to the list at the end we call the add method:

    Age.add (50)

But we can add it in any position within the list by the add method with two parameters, in the first we indicate the position and in the second the value to be stored:

    Ages.add (0, 17)

By means of the method count and passing a lambda we can count all the elements that fulfill a condition:

    Print ("Number of persons of legal age:")
    Val cont = ages.count {it >= 18}
    Println (cont)

We can also remove all the elements of the list that fulfill a certain condition indicated a lambda:

    Ages.removeAll {it == 12}
    Println ("List of ages after deleting those that are 12 years old")
    Println (ages)

If we want to know all the properties and methods of MutableList we can visit the documentation of the standard library of Kotlin.

Problem 4

Create a mutable list of 20 items with random values between 1 and 6.
Count how many items are stored in the value 1.
Delete items that store a 6.

Project 176

fun main (args: Array <String>) {
    val list: MutableList <Int> = MutableList (20) {((Math.random () * 6) + 1) .toInt ()}
    println ("Complete List")
    println (list)
    val cont = list.count {it == 1}
    println ("Number of items with the value 1: $cont")
    list.removeAll {it == 6}
    println ("List after deleting items with value 6")
    println (list)
}

To create a list of 20 elements we use the MutableList function and we pass in the first parameter the number of elements and in the second parameter a lambda generating random values between 1 and 6.

To count the elements that store a 1 we use the count function and pass a lambda with the condition that must be met to be counted:

    Val cont = lista.count {it == 1}

To remove, we call the removeAll method:

    List.removeAll {it == 6}

Problem 5

Implement a class called Person that will have properties like their name and age.
Define in addition two methods, one that prints the properties and another shows if it is of age.

Define a mutable list of objects in the Person class.
Print the data of all people.
Print how many people are of age.

Project 177

class Person (var name: String, var age: Int) {

    fun print() {
        println ("Name: $name and has an age of $age")
    }

    fun MajorAge () {
        if (age >= 18)
        println ("Is an adult $name")
        else
        println ("You are not of age $name")
    }
}

fun main (args: Array <String>) {
    val people: MutableList <Person>
    people = mutableListOf (Person ("John", 22), Person ("Ana", 19), Person ("Mark", 12))
    println ("List of all persons")
    people.forEach {it.print ()}
    val cont = people.count {it.age >= 18}
    println ("The number of adults is $cont")
}

We declare the Person class with two properties and two methods:

Class Person (var name: String, var age: Int) {

    Fun print () {
        Println ("Name: $name and has an age of $age")
    }

    Fun MajorAge () {
        If (age> = 18)
            Println ("Is an adult $name")
        Else
            Println ("You are not of age $name")
    }
}

We define a mutable list that stores Person components:

Fun main (args: Array <String>) {
    Val people: MutableList <Person>

We create the list using the mutableListOf  method and pass the reference to three objects of the Person class:

    People = mutableListOf (Person ("John", 22), Person ("Ana", 19), Person ("Mark", 12))

We print all the data of the people processing each object stored in the list by calling the forEach method and the lambda function by calling the print method of each person:

    Println ("List of all persons")
    people.forEach {it.print ()}

Finally, we count the number of people of age:

    Val cont = people.count {it.age> = 18}
    Println ("The number of adults is $cont")

Problems proposed

  • Create an immutable list of 100 integers with random values between 0 and 20.
    count how many are between 1 and 4, 5 and 8 and how many between 10 and 13.
    Print if the value 20 is present in the list.
  • Make a class that represents an Employee. Define properties as your name and your salary.
    Define a mutable list with three employees.
    Print employee data.
    Calculate how much the company spends in salaries.
    Add a new employee to the list and recalculate the salary expense.
  • Load by keyboard and store in an unchanging list the heights of 5 people (Float values)
    Get the average of them. Count how many people are higher than average and how many are lower.
Solution

About The Author

Related posts

Leave a Reply