Is it possible to replace all loops while with a loops for in this code?

fun getAnagrams(words: Array): MutableList<ArrayList> {
var array: Array = Array(words.size) { WordWithIndex(words[it], it) }
array = wordArraySort(array)
val anagrams: MutableList<ArrayList> = ArrayList()
var i=0
while (i < array.size - 1) {
if (array[i].word == array[i + 1].word) {
val newGroup: MutableList = ArrayList()
newGroup.add(words[array[i].index])
newGroup.add(words[array[++i].index])
while (i < array.size - 1 && array[i].word == array[i + 1].word) {
i++
newGroup.add(words[array[i].index])
}
anagrams.add(newGroup as ArrayList)
}
i++
}

return anagrams

}

This isn’t even valid Kotlin. Are you sure changing the loops is your priority here?

Yes, it is possible. However, your code has multiple problems. For example:

while (i < array.size - 1) {
    if (array[i].word == array[i + 1].word) {

This throws an exception for the last item of the array if I’m right.

The right way would be to clean up this code first, probably switching to for or even forEach would be part of the cleanup.