How to remove duplicates from a list

How can I remove duplicates from a list given an equivalence function?

In my case I have a List[List[Location]] where Location is defined in my application. I want to remove according to the following equivalence function.

def equivalenceFunction(a:List[Location],b:List[Location]):Boolean = 
   a.toSet == b.toSet

I could build a Map mapping a.toSet to a and then take the values of the map. Is that the correct way?

  def uniquifyGrid(grid:List[List[Location]]):List[List[Location]] = {
    (for{ item <- grid}
      yield item.toSet -> item)
      .toMap
      .values
      .toList
  }
list.distinctBy(_.toSet)
3 Likes

cool. distinctBy another name for uniquify and removeDuplicates