I am attempting to find the difference of 2 arraylists in kotlin i.e the elements in the first arraylist that are not included in the second arraylist. The code below I believe would work for listOf but I need it to work for arraylists of strings structure instead with the same names i.e first, second and difference should all be arraylists of strings.
fun main() {
private var first = ArrayList<String>()
private var second = ArrayList<String>()
private var difference = ArrayList<String>()
first.add(“a”)
first.add(“b”)
first.add(“c”)
first.add(“d”)
first.add(“e”)
second.add(“a”)
second.add(“b”)
second.add(“c”)
val difference = first.minus(second)
println(difference) // [d, e]
}
CodePudding user response:
You can use arrayListOf
:
fun main() {
val first = arrayListOf("a", "b", "c", "d", "e")
println("first type: %s".format(first.javaClass.kotlin.qualifiedName))
val second = arrayListOf("a", "b", "c")
println("second type: %s".format(second.javaClass.kotlin.qualifiedName))
val difference = first.minus(second)
println(difference)
println("difference type: %s".format(difference.javaClass.kotlin.qualifiedName))
}
Or instead, add the elements to the ArrayList's one by one if desired:
fun main() {
val first = ArrayList<String>()
first.add("a")
first.add("b")
first.add("c")
first.add("d")
first.add("e")
println("first type: %s".format(first.javaClass.kotlin.qualifiedName))
val second = ArrayList<String>()
second.add("a")
second.add("b")
second.add("c")
println("second type: %s".format(second.javaClass.kotlin.qualifiedName))
val difference = first.minus(second)
println(difference)
println("difference type: %s".format(difference.javaClass.kotlin.qualifiedName))
}
Output:
first type: java.util.ArrayList
second type: java.util.ArrayList
[d, e]
difference type: java.util.ArrayList