Home > OS >  How to remove item and replace it with a new one at the same place in ArrayList?
How to remove item and replace it with a new one at the same place in ArrayList?

Time:10-28

I have ArrayList for example:

var list: ArrayList<String> = arrayListOf("one", "two", "three")

And I need to replace "two" with "four", so I need to delete it and replace at the same place with "four" but i don't know where is "two" is located. How can i do that?

CodePudding user response:

In the most simple form:

val list = arrayListOf("one", "two", "three")

// get the index of the item to swap
val index = list.indexOf("two")

// set the item at index to the new value
list[index] = "four"

// result is ["one", "four", "three"]

You may want to check if the list actually contains the value, by asserting that index >= 0

CodePudding user response:

The simpler way is finding the index of the element you want to replace and the set the new value for it as follows:

var list: ArrayList<String> = arrayListOf("one", "two", "three")
int index = list.indexOf("two");
list.set(index, "four");

CodePudding user response:

You could use something like

fun <T> Iterable<T>.replace(old: T, new: T) = map { if (it == old) new else it }

Usage: list.replace("two", "four")

  • Related