Kotlin forEach & forEachIndexed method on Array, List, Map collection example

kotlin-foreach-foreachIndexed-method-on-array-list-map-collection-example-feature-image

In the tutorial, Grokonez will show you how to use Kotlin forEach and forEachIndexed methods to loop through Kotlin Array, List, Map collections.

In Kotlin, you can use the forEachIndexed function to iterate over a collection and access both the element and its index. This function is available for all collections that implement the Iterable interface.

Here’s an example of using forEachIndexed to iterate over a list:

val list = listOf(1, 2, 3, 4, 5)
list.forEachIndexed { index, element ->
  println("Element at $index is $element")
}
Element at 0 is 1
Element at 1 is 2
Element at 2 is 3
Element at 3 is 4
Element at 4 is 5

You can also use forEachIndexed with a map:

val map = mapOf("a" to 1, "b" to 2, "c" to 3)
map.forEachIndexed { index, (key, value) ->
  println("Element at $index is $key -> $value")
}

This will print the following output:

Element at 0 is a -> 1
Element at 1 is b -> 2
Element at 2 is c -> 3

Note that the index of the elements starts at 0. If you want to start the index at a different number, you can use the withIndex function instead, which allows you to specify a custom start index.

Here is an example of using the forEachIndexed function in Kotlin:

fun main() {
    val names = listOf("Alice", "Bob", "Charlie", "Dave")

    names.forEachIndexed { index, name -> 
        println("$index: $name")
    }
}

This will output the following:

0: Alice
1: Bob
2: Charlie
3: Dave

The forEachIndexed function takes a lambda function as an argument, which is passed the index and the element of each item in the collection. The lambda function is then applied to each element in the collection. In this example, we are printing out the index and the name for each element in the names list.

You can also use the forEachIndexed function with any other type of collection, such as an array or a set.

I. forEach method

forEach method is used to performs the given action on each element.

1. with Array

Method signature:

public inline fun  Array.forEach(action: (T) -> Unit): Unit

Practice:

val simpleArray = arrayOf(1, 2, 3,  4)
simpleArray.forEach { println(it) }
// print on console
// ->
/*
	1
	2
	3
	4		
*/

val customerArray = arrayOf(Customer("Craig", 45),
								Customer("Amos", 23),
								Customer("Jack", 20))

customerArray.forEach { println(it) }
// println on console
// ->
/*
	Customer(name=Craig, age=45)
	Customer(name=Amos, age=23)
	Customer(name=Jack, age=20) 
*/
2. with List

Method signature:

public inline fun  Iterable.forEach(action: (T) -> Unit): Unit

Practice:

val simpleList = listOf(5, 6, 7, 8)
simpleList.forEach{println(it)}
// print on console
// ->
/*
	5
	6
	7
	8
*/

val customerList = listOf(Customer("Smith", 26),
								Customer("Peter", 43),
								Customer("Mary", 27))
customerList.forEach { println(it) }
// print on console
// ->
/*
	Customer(name=Smith, age=26)
	Customer(name=Peter, age=43)
	Customer(name=Mary, age=27) 
*/
3. with Map

Method Signature:

public inline fun  Map.forEach(action: (Map.Entry) -> Unit): Unit

Practice:

val simpleHashMap = hashMapOf(1 to "one", 2 to "two", 3 to "three" )
simpleHashMap.forEach{ println(it) }
// println on console
// ->
/*
	1=one
	2=two
	3=three
*/

val customerHashMap = hashMapOf("Smith" to Customer("Smith", 26),
								"Peter" to Customer("Peter", 43),
								"Mary" to Customer("Mary", 27))
customerHashMap.forEach{ println(it) }
// println on console
// ->
/*
	Smith=Customer(name=Smith, age=26)
	Peter=Customer(name=Peter, age=43)
	Mary=Customer(name=Mary, age=27)
*/

II. forEachIndexed method

forEachIndexed method performs the given action on each element, providing sequential index with the element.

1. with Array

Method Signature:

public inline fun  Array.forEachIndexed(action: (index: Int, T) -> Unit): Unit

Practice:

simpleArray.forEachIndexed{index, element -> println("index = $index, element = $element")}
// print on console
// ->
/*
	index = 0, element = 1
	index = 1, element = 2
	index = 2, element = 3
	index = 3, element = 4 
*/
customerArray.forEachIndexed{index, customer -> println("index = $index, customer = $customer")}
// print on console
// ->
/*
	index = 0, customer = Customer(name=Craig, age=45)
	index = 1, customer = Customer(name=Amos, age=23)
	index = 2, customer = Customer(name=Jack, age=20)
*/
2. with List

Method signature:

public inline fun  Iterable.forEachIndexed(action: (index: Int, T) -> Unit): Unit

Practice:

simpleList.forEachIndexed{index, element -> println("index = $index, element = $element")}
// print on console
// ->
/*
	index = 0, element = 5
	index = 1, element = 6
	index = 2, element = 7
	index = 3, element = 8
*/

customerList.forEachIndexed{index, customer -> println("index = $index, customer = $customer")}
// print on console
// ->
/*
	index = 0, customer = Customer(name=Smith, age=26)
	index = 1, customer = Customer(name=Peter, age=43)
	index = 2, customer = Customer(name=Mary, age=27)
*/

III. Full sourcecode

package com.javasampleapproach.kotlinforeach

data class Customer(
	val name: String,
	val age: Int
)

fun main(args : Array) {
	
	println("#############################################################")
	println("---------------------I. forEach() method---------------------")
	println("#############################################################")
	
	println("-------------1. work with Array-------------")
	val simpleArray = arrayOf(1, 2, 3,  4)
	simpleArray.forEach { println(it) }
	// print on console
	// ->
	/*
		1
		2
		3
		4		
 	*/
	
	val customerArray = arrayOf(Customer("Craig", 45),
									Customer("Amos", 23),
									Customer("Jack", 20))
	
	customerArray.forEach { println(it) }
	// println on console
	// ->
	/*
		Customer(name=Craig, age=45)
		Customer(name=Amos, age=23)
		Customer(name=Jack, age=20) 
 	*/
	
	println("-------------2. work with List-------------")
	val simpleList = listOf(5, 6, 7, 8)
	simpleList.forEach{println(it)}
	// print on console
	// ->
	/*
		5
		6
		7
		8
 	*/
	
	val customerList = listOf(Customer("Smith", 26),
									Customer("Peter", 43),
									Customer("Mary", 27))
	customerList.forEach { println(it) }
	// print on console
	// ->
	/*
		Customer(name=Smith, age=26)
		Customer(name=Peter, age=43)
		Customer(name=Mary, age=27) 
 	*/
	
	println("-------------3. work with HashMap -------------")
	val simpleHashMap = hashMapOf(1 to "one", 2 to "two", 3 to "three" )
	simpleHashMap.forEach{ println(it) }
	// println on console
	// ->
	/*
		1=one
		2=two
		3=three
 	*/
	
	val customerHashMap = hashMapOf("Smith" to Customer("Smith", 26),
									"Peter" to Customer("Peter", 43),
									"Mary" to Customer("Mary", 27))
	customerHashMap.forEach{ println(it) }
	// println on console
	// ->
	/*
		Smith=Customer(name=Smith, age=26)
		Peter=Customer(name=Peter, age=43)
		Mary=Customer(name=Mary, age=27)
 	*/
	
	// II. forEachIndexed() method
	println("#############################################################")
	println("-----------------II. forEachIndexed() method-----------------")
	println("#############################################################")
	// 1. work with Array
	println("-------------1. work with Array-------------")
	simpleArray.forEachIndexed{index, element -> println("index = $index, element = $element")}
	// print on console
	// ->
	/*
		index = 0, element = 1
		index = 1, element = 2
		index = 2, element = 3
		index = 3, element = 4 
 	*/
	customerArray.forEachIndexed{index, customer -> println("index = $index, customer = $customer")}
	// print on console
	// ->
	/*
		index = 0, customer = Customer(name=Craig, age=45)
		index = 1, customer = Customer(name=Amos, age=23)
		index = 2, customer = Customer(name=Jack, age=20)
 	*/
	
	// 2. work with List
	println("-------------2. work with List-------------")
	simpleList.forEachIndexed{index, element -> println("index = $index, element = $element")}
	// print on console
	// ->
	/*
		index = 0, element = 5
		index = 1, element = 6
		index = 2, element = 7
		index = 3, element = 8
 	*/
	
	customerList.forEachIndexed{index, customer -> println("index = $index, customer = $customer")}
	// print on console
	// ->
	/*
		index = 0, customer = Customer(name=Smith, age=26)
		index = 1, customer = Customer(name=Peter, age=43)
		index = 2, customer = Customer(name=Mary, age=27)
 	*/
}
0 0 votes
Article Rating
Subscribe
Notify of
guest
1.7K Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments