I have an initial list of elements in common
val commonList = mutableListOf<String>
I have the following object
ClassObject(val title: String, val subjects: List<String>)
Assuming you have such a list with initial data
val list = listOf<ClassObject> /* With a size of 1000 samples */
How can I iterate the initial list "list" and look in the list of "subjects" for the elements that are not in "commonList" and add them to this last list.
I had thought of a nested for loop, but it would require a lot of power and time.
list.forEach { c ->
c.subjects.forEach { s ->
if (s !in commonList)
commonList.add(s)
}
}
CodePudding user response:
You should use MutableSet instead of MutableList for this purpose. Using an in
check on a Set does not require iteration so it is far more performant. It would also make your code a lot simpler, because it won't redundantly add items, so you can simply use an addAll
call on it to achieve the same thing as if you had first checked if each item is in the set first.
val commonSet = mutableSetOf<String>()
val list = listOf<ClassObject>( /*...*/ )
for (classObject in list) {
commonSet.addAll(classObject.subjects)
}
In Big-O notation, the above is O(n), whereas your original code is O(n^2).
CodePudding user response:
So to paraphrase, it seems you want to accumulate all unique entries from your nested list
into a flat list commonList
.
In which case, using a MutableSet
would be a good idea. I'm not familiar with the Kotlin implementation of sets, but traditionally they are like hashmaps that don't map keys to values but instead hold unique keys. The difference from a simple List
being that they are internally more sophisticated than a plain array, and benefit from faster collision look-ups.
In conclusion, you can't really avoid the nested loop, but you can eliminate the wasteful !in
check. If you must end up with a list at the end, you can always call toList
on the set.