Find all occurrences of an element in a Kotlin List
This article explores different ways to find all occurrences of an element in a Kotlin List.
1. Using filter()
function
To find the indices of all occurrences of an element in a list, you can create a range of the valid indices and apply a filter over it to collect all matching elements with the given value.
1 2 3 4 5 6 7 8 9 10 |
fun main() { val values = listOf("A", "B", "C", "B", "D") val target = "B" val indices = values.indices .filter { values[it] == target } .toList() println(indices) } |
Output:
[1, 3]
The above solution iterates over the list’s indices and not the list. If you need an Int array, use toIntArray()
function instead:
1 2 3 4 5 6 7 8 9 10 |
fun main() { val values = listOf("A", "B", "C", "B", "D") val target = "B" val indices = values.indices .filter { values[it] == target } .toIntArray() println(indices.contentToString()) } |
Output:
[1, 3]
2. Using Loop
Alternatively, you can write our custom routine for this trivial task using a loop:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun main() { val values = listOf("A", "B", "C", "B", "D") val target = "B" val indices = mutableListOf<Int>() for (i in values.indices) { if (values[i] == target) { indices.add(i) } } println(indices) } |
Output:
[1, 3]
That’s all about finding all occurrences of an element in a Kotlin List.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)