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.

Download Code

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:

Download Code

Output:

[1, 3]

2. Using Loop

Alternatively, you can write our custom routine for this trivial task using a loop:

Download Code

Output:

[1, 3]

That’s all about finding all occurrences of an element in a Kotlin List.