I was wondering if I can tune the following Scala code :
def removeDuplicates(listOfTuple: List[(Class1,Class2)]): List[(Class1,Class2)] = {
var listNoDuplicates: List[(Class1, Class2)] = Nil
for (outerIndex <- 0 until listOfTuple.size) {
if (outerIndex != listOfTuple.size - 1)
for (innerIndex <- outerIndex + 1 until listOfTuple.size) {
if (listOfTuple(i)._1.flag.equals(listOfTuple(j)._1.flag))
listNoDuplicates = listOfTuple(i) :: listNoDuplicates
}
}
listNoDuplicates
}
Usually if you have someting looking like:
can be converted in something like:
So here we can first use a map to force the unicity of flags. Supposing the flag has a type F:
Then the remaining tuples can be extracted from the map and converted to a list:
It will keep the last tuple encoutered, if you want to keep the first one, replace
foldLeftbyfoldRight, and invert the argument of the lambda.Example:
Edit: If you need to retain the order of the initial list, use instead: