【问题标题】:In Scala what is the most efficient way to remove elements in a list based on being similar to another element?在 Scala 中,根据与另一个元素的相似性来删除列表中元素的最有效方法是什么?
【发布时间】:2021-09-23 15:53:34
【问题描述】:

我有一个长长的对象列表,大约 300 个,列表中的每个对象都具有以下数据结构:

case class MyObject(id: String,
                    name: String,
                    colour: String,
                    price: Int
                    height: Int
                    width: Int,
                    desc: String)

我无法确定浏览列表的最佳方法是什么,然后为每个对象删除具有相同名称、颜色、价格、高度和宽度的任何其他对象。请注意,这不是简单的重复数据删除,因为 ids 和 desc 可能不同。输入和输出需要保持List[MyObject],我事先不知道哪些对象是重复的。

这是我最初的可行解决方案,但不确定在处理大型列表时它是最有效的方法。

def removeDuplicates(originalList: List[MyObject]): List[MyObject] = {

  def loop(remaining: List[MyObject], acc: List[MyObject]): List[MyObject] = {
    remaining match {
      case head :: tail =>
        val listOfDuplicates = tail.filter{ x =>
          x.name == head.name &&
          x.colour == head.colour &&
          x.price == head.price &&
          x.height == head.height &&
          x.width == head.width
        }

        val deDupedTail = tail.filter(!listOfDuplicates.contains(_))

        loop(deDupedTail, acc ::: listOfDuplicates)
      case Nil => acc
    }
  }
  val listOfDuplicateObjects = loop(originalList, List())
  originalList.filter(!listOfDuplicateObjects.contains(_))
}

【问题讨论】:

  • 这是一个很好的开始。您可以通过将迭代值累积到像 Set 这样的散列数据结构中来提高效率,这将使您进行 O(1) 搜索而不是 O(n)。

标签: list scala loops filter


【解决方案1】:

不确定它是否最有效,但恕我直言,它很优雅:

originalList.distinctBy(o => (o.name, o.colour, o.price, o.height, o.width))

【讨论】:

  • 天啊,它是内置的。Scala 的庞大集合库从未停止让我惊叹。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-05
  • 2016-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多