Home / Programming / Kotlin / Kotlin ArrayList and Loops Example

Kotlin ArrayList and Loops Example

Kotlin ArrayList

Kotlin ArrayList is also very similar to Java Arraylist.

ArrayList<T> is the resizable-array implementation of the List interface.

The ArrayList class has only a few methods in addition to the methods available in the List interface.

val myArrayList = arrayListOf("John", "Fred", "McKinsey", "Morgan", "Sarah") //an arraylist of my friends
val newFriendList = arrayListOf("Musa", "Victor", "Timothy")
myArrayList.add(0, newFriendList[0])
for (e in myArrayList){
 print("$e -")
} // Musa -John -Fred -McKinsey -Morgan -Sarah
myArrayList.removeAt(0) // removes 'Musa' which is at postion 1
val allOfMyFriends = myArrayList + newFriendList
for(element in allOfMyFriends){
 print("$element -")
} // John -Fred -McKinsey -Morgan -Sarah -Musa -Victor -Timothy
println(allOfMyFriends.size) // 8 
println(allOfMyFriends.isEmpty) // false
 
val isRemoveFredSuccesful: boolean  = allOfMyFriends.remove("Fred") // searches for 'Fred', removes it, if successful returns True else returns false
println(isRemoveFredSuccesful) // True

val isRemoveCooperSuccesful: boolean = allOfMyFriends.remove("Cooper")
println(isRemoveCooperSuccesful) // FALSE

val friendSubArrayList = allOfMyFriends.subList(2,5)
println(friendSubArrayList) //[McKinsey, Morgan, Sarah]

Kotlin Loop

Loops allow us to repeat a certain piece of our code over a specified number of times.

For Loops

for loops should be used when we know how many iterations we need in advance.

Let’s say you want to print ‘Hello World’ one  hundred times (iteration), we do not need to write the statement a hundred times in a hundred lines of code, loops would make it easy to achieve in 3 lines of code

for (index in 1 .. 100){
 println("Hello World $index")
} 
/* 
Hello World 1
Hello World 2
...   
*/

val langs = listOf("Kotlin", "Java", "Javascript", "Python", "Php")
for ((index, value) in langs.withIndex()){ //Tryin to get items in the list together with it's indez
    println("$index - $value") 
}
/*
   0 - Kotlin
   1 - Java
   2 - Javascript
   3 - Python
   4 - Php
*/

While Loop

while loops should be used when we do not know how many iterations we need, example is when we want to read a text file line by line. The text file will vary from one application to the other, therefore we cannot know the exact number of lines in the file for different applications. Here while loops are suitable

var x = 9 // assuming the unknown number of lines = 9
while(x > 0 ){
    println(x)
    x-- //decrement x by 1 i.e x = x - 1
}

The above code is less concise and more error prone as compared to for loop. We had to manually decrement x.  for loop is a better choice when trying to iterate a specified number of times.

Within the while loop parenthesis we can have any condition we want, as demonstrated below

// Having Any Condition within While Loop
while(user.isOnline()){
    println("Welcome!")
}

Naming our Loops

you may be wondering why would i want to give my loop a name? if you have nested loops as shown below

for (i in 1..5){
    for (j in 1..5){
        if (i-j == 2) break
        println("$i - $j = ${i-j}")
    }
}

/*
OUTPUT 
1 - 1 = 0
1 - 2 = -1
1 - 3 = -2
1 - 4 = -3
1 - 5 = -4
2 - 1 = 1
2 - 2 = 0
2 - 3 = -1
2 - 4 = -2
2 - 5 = -3
4 - 1 = 3 << 4 - 2 was skipped
5 - 1 = 4
5 - 2 = 3

*/

you may want to break line 1 instead of breaking line 5 whenever the condition on line 3 is satisfied. In other to do that, you write the code below by appending ‘outer’ to your loop

outer@ for (i in 1..5){
   for (j in 1..5){
      if (i-j == 2) {
        break@outer // attach the name of our loop without any space
      }
      println("$i - $j = ${i-j}")
   }
}

/*
OUTPUT
1 - 1 = 0
1 - 2 = -1
1 - 3 = -2
1 - 4 = -3
1 - 5 = -4
2 - 1 = 1
2 - 2 = 0
2 - 3 = -1
2 - 4 = -2
2 - 5 = -3 << 3-1 = 2 halted/broke the loop 
*/

the continue statement works just the same way

You may not find yourself using this very often but if you come into a situation that you want to use something like this, now you know how you can do it!

Thanks for reading, do not forget to try out the code for yourself Try out Kotlin

About Edge Developer

Hello there, my name is Opeyemi Olorunleke. I am a Software Developer (majorly Android, GitHub Profile), Digital Marketer, Udemy Instructor, Technical Writer, Blogger & Webmaster.

Check Also

RecyclerView Multi-Select using KOTLIN

Implementing multi-select on a Recycler View can be tricky and complicated. However, by the end …

Leave a Reply

Your email address will not be published. Required fields are marked *