Updated April 4, 2023
Introduction to Kotlin forEach
Kotlin forEach is one of the loop statements that are more traditionally used to do other loops like while loops the loops are used to get each other and every element of the collection, list and to perform the actions on each and every elements of the list like an array and other collection list it is like the function approach towards the traditional for-loop ways for both for loops and forEach are the same generating outputs from an array or the list is also more useful if we use it with more functional operators with more concise and smart.
Syntax of Kotlin forEach
In kotlin language, it uses many kinds of loops to implement the mobile-based application. Each type of looping statement will be covered and utilized with the other conditional statements on the programming requirement.
fun demo()
{
CollectionMethod(input values).forEach(fun(variable:datatype))
{
---some conditional statement depends on the requirement---
}
}
fun main()
{
demo()
}
The above codes are one of the basic syntaxes for utilizing the forEach() loop in different areas. We can call forEach() loop method to perform the action on each and every element of the list. It is like a functional approach towards the perform traditional for using the loop paths.
How forEach Works in Kotlin?
- The forEach loop is one of the iteration loops for but we can call additional functions with the variable using the datatype. It also calls with the other util and packages like collections, files,s, etc. If we use a collection concept like a list, map the datas are passing to the array type and the values are calculated using the index-based format. So that the datas are stored and retrieved using the index format regularly the list and map values are additionally called using the forEach() loop statement with functions are calling as the parameter arguments.
- It can also support lambda and other anonymous variables and functions for both local and non-local types of values that returned from the expression like lambda and other regular expressions. In array and other list collections, the for and forEach loops are the same when generating the output results from the array or the collection list. The functional operators are supported and used with the application to perform the other user-defined and default tasks from the native users.
- We can use nested forEach loop to iterate all the values it will be both implicit and explicit parameter arguments. The implicit parameters are enclosing and enforced for the other lambda and anonymous statements.
Examples of Kotlin forEach
Given below are the examples mentioned:
Example #1
Code:
class States(val stname : String, val stcapital : List<Places>)
class Places(val pname : String, val cities : List<String>)
class Months {
val mn = listOf("January", "February","March","April","May","June","July","August","September","October","November","December")
val electrnoics = listOf("Ups","Inverters","Gadgets","Desktop PCs","Microwave Oven","Fridge","Washing Machine","mobile")
val laptops = listOf("Dell latitude", "dell inspiron","sony","acer","samsung","lenovo","apple")
val stplaces = listOf(
States("Delhi", listOf(Places("Noida", laptops),
Places("Darjeeling", mn))),
States("Tamilnadu", listOf(Places("chennai", electrnoics))))
}
data class Users(
val uname: String,
val uid: Int
)
fun main() {
var ct=Months()
ct.stplaces.forEach { c -> println(c.stname) }
println("Welcome To My Domain")
println("Its the first example that related to the kotlin forEach() loop")
println("First we passed the input as Arrays")
val ar = arrayOf(9, 8, 7, 6,5,4,3,2,1)
ar.forEach { println(it) }
val userar = arrayOf(Users("siva", 41),
Users("raman", 44),
Users("sivaraman", 45))
userar.forEach { println(it) }
println("We used forEach in collection List classes and its methods")
val inp = listOf(4, 2, 1, 3)
inp.forEach{println(it)}
val userlst = listOf(Users("kumar", 42),
Users("arun", 44),
Users("arun kumar", 46))
userlst.forEach { println(it) }
println("We used forEach loop with collection class called HashMap and its methods")
val userhshmap = hashMapOf(41 to "Sreesha", 42 to "Sunny", 43 to "Kutty" )
userhshmap.forEach{ println(it) }
val usrmap = hashMapOf("kumar" to Users("kumar", 42),
"arun" to Users("arun", 44),
"arun kumar" to Users("arun kumar", 46))
usrmap.forEach{ println(it) }
}
Output:
In the first example, we used the collection concept additionally to iterate the values using forEach() loop iteration.
Example #2
Code:
val userss: MutableList<Int> = mutableListOf(41, 22, 33)
val details: List<Int> = userss
fun userdetails(addUsers: Int) {
userss.add(addUsers)
}
fun demo2(): List<Int> {
return details
}
fun main() {
println("Welcome To My Domain its the second example related to the forEach loop statements")
println("We used forEachIndexed() method")
val ar = arrayOf(9, 8, 7, 6,5,4,3,2,1)
println(" We used the input as Array format")
ar.forEachIndexed{keyindx, keyelmnt -> println("keyindx = $keyindx, keyelmnt = $keyelmnt")}
ar.forEachIndexed{keyindx, Users -> println("keyindx = $keyindx, Users = $Users")}
var inp = listOf(4, 2, 1, 3)
println("We used forEach() method with List collection")
inp.forEachIndexed{keyindx, keyelmnt -> println("keyindx = $keyindx, keyelmnt = $keyelmnt")}
ar.forEachIndexed{keyindx, Users -> println("keyindx = $keyindx, Users = $Users")}
userdetails(41)
println("Total output details: ${demo2().size}")
demo2().forEach {
i -> println("Some useful info on user $i")
}
}
Output:
Here we used forEachIndexed loop to iterate the elements with key and value format.
Example #3
Code:
import java.util.Scanner;
fun demo(x: Any) = when (x) {
is String -> x.startsWith("Welcome To My Domain its the third example that relates to the Kotlin forEach")
else -> false
}
fun main() {
println("Welcome To My Domain its the third example related to the forEach loop statements")
println("#############################################################")
val arinp = arrayOf(9,3,6)
arinp.forEach { n -> println(n * n) }
arinp.forEach { println(it*it) }
var str = Scanner(System.`in`)
print("Please enter your Textile Shop:")
var texName = str.nextInt()
var out = when(texName){
1->"Chennai Silks"
2->"Saravana Stores"
3->"Bharani"
4->"SPJ"
5->"AllenSolly"
6->"Jockey"
7->"Arrow"
8->"DSP"
9->"Minister White"
10->"Park Avenue"
11->"Peter England"
12->"Reymond"
13->"Levis"
else -> {
println("Your brand is not listed here")
}
}
println(out)
var new = "Welcome To My Domain its the third example that relates to the Kotlin forEach concept"
var res = demo(new)
if(res) {
println("Yes, Your brand is listed Welcome To My Domain its the third example that relates to the Kotlin forEach")
}
else {
println("No, Sorry your brand is not listed here Kindly try with one more and please stay with our application and spent your valuable time for us thanks")
}
}
Output:
In the final example, we used when i.e. switch statement is used to print the case statement on the console with forEach loop iteration.
Conclusion
In the kotlin language, we used different kinds of loops to store and retrieve the elements for the iterating process. Also, the iteration stops until the loop is terminated by the user end or any other exception like arrayindexoutofbound exception like that the loop is existed by the kotlin compiler and execution time.
Recommended Articles
This is a guide to Kotlin forEach. Here we discuss the introduction, how forEach works in kotlin? and examples for better understanding. You may also have a look at the following articles to learn more –