Kotlin forEach Loop

Before we jump on for each that is our topic let’s first discuss the for each loop in java.

For each loop in Java would like to be:

class For_Each  	
{
    public static void main(String[] arg)
    {
        {
            int[] marks = { 12, 32, 97, 126, 130 };
              
            int highest_marks = maximum(marks);
            System.out.println("The highest score is " + highest_marks);
        }
    }
    public static int maximum(int[] numbers)
    { 
        int maxSoFar = numbers[0];
          
        // for each loop
        for (int num : numbers) 
        {
            if (num > maxSoFar)
            {
                maxSoFar = num;
            }
        }
    return maxSoFar;
    }
}

Output:

The Highest Score is 130

Kotlin forEach Loop

Kotlin forEach Loop

Kotlin for each loop also does the same work for us. It also provides the functionality to re-run the same lines of code again and again but has certain advantages that help to reduce the code and make it easy to use for the programmers and the developers. It also helps us to increase the efficiency of the code.

So let us see the demo for the for each loop.

Suppose we have a list and we want to print it. The values we want to insert are John, Ishank, Rocky, Aditya.

fun main ( ){

	val people : List<Person> = listof(

		Person ("John"),
		Person ("Ishank"),
		Person ("Rocky"),
		Person ("Aditya")
	)

	people.forEach {
		println(it)
	}
}

Output

Person(name=John)
Person(name=Ishank)
Person(name=Rocky)
Person(name=Aditya)

In the above code, we have taken the values of the persons and print them.

Suppose the values which we are getting, we want them to be in the capital letters that is the uppercase. So how we can do it in kotlin. We have a single function that helps us to do the same. Let us see how we can do the same with the code.

fun main ( ){

   val people : List<Person> = listOf(
           Person("John"),
           Person("Ishank"),
           Person("Rocky"),
           Person("Aditya")

   )
       

            people.map{ it.name }.forEach{ println(it.toUpperCase())}
   }


data class Person(val name: String)

Output:

JOHN
ISHANK
ROCKY
ADITYA

In the above code, we have used the function toUpperCase(). This is the inbuilt function which is used to make the values in the uppercase.

Now suppose we get a task to reverse the letters of every single name in the output. For this also kotlin has given us a very simple way to do so. We just have to use the in-built function. Let us see how we can do it in Kotlin.

fun main ( ){

   val people : List<Person> = listOf(
           Person("John"),
           Person("Ishank"),
           Person("Rocky"),
           Person("Aditya")

   )


            people.map{ it.name }.map{ it.toUpperCase()}.forEach { println(it.reversed()) }
   }


data class Person(val name: String)

Output:

NHOJ
KNAHSI
YKCOR
AYTIDA

We can see in the output that all the names have been reversed. This is done by the function named as the reversed (). This is the in-built function available to us by the kotlin. Also, the output appears to be the uppercase as we have not removed the uppercase function.

So this is the benefit of using the for-each loop which offers many functions such as it reduces the lines of code saving the developer’s time, effort, and of course the cost.

Leave a Comment