I have a list of unsorted integers and I want to find those elements which have duplicates.
val dup = List(1,1,1,2,3,4,5,5,6,100,101,101,102
Another approach is to use foldLeft and do it the hard way.
We start with two empty sets. One is for elements that we have seen at least once. The other for elements that we have seen at least twice (aka duplicates).
We traverse the list. When the current element has already been seen (seen(cur)) it is a duplicate and therefore added to duplicates. Otherwise we add it to seen.
The result is now the second set that contains the duplicates.
We can also write this as a generic method.
def dups[T](list: List[T]) = list.foldLeft((Set.empty[T], Set.empty[T])){ case ((seen, duplicates), cur) =>
if(seen(cur)) (seen, duplicates + cur) else (seen + cur, duplicates)
}._2
val dup = List(1,1,1,2,3,4,5,5,6,100,101,101,102)
dups(dup) //Set(1,5,101)