Home > database >  Is there an easy way for deep cloning a list in Kotlin?
Is there an easy way for deep cloning a list in Kotlin?

Time:01-15

I need to clone an ArrayList of type Any which contains only strings and Arraylists that contain only strings and arrayLists that ... . A shallow copy does not work for me as I need to have every element cloned. My idea is to loop through every element or to convert the ArrayList to a String and than back to an ArrayList ( using the commas and brackets in the string). Any idea how to do this easier? ( Java answers are appreciated too as I think it is convertable to Kotlin)

CodePudding user response:

You can use a simple recursive method to deep copy every nested list. Here's a demonstration using Java streams:

List<?> deepCopy(List<?> list) {
    return list.stream()
            .map(e -> e instanceof List ? deepCopy((List<?>)e) : e)
            .collect(Collectors.toList());
}

CodePudding user response:

fun cloned(arrayList: ArrayList<Any>): ArrayList<Any> {
  return arrayList.map {
    when (it) {
      is ArrayList<*> -> cloned(it.toList() as ArrayList<Any>)
      else            -> it
    }
  } as ArrayList<Any>
}
  •  Tags:  
  • Related