在 Scala 中,如何从列表中删除重复项?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7135627/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Scala how do I remove duplicates from a list?
提问by deltanovember
Suppose I have
假设我有
val dirty = List("a", "b", "a", "c")
Is there a list operation that returns "a", "b", "c"
是否有返回“a”、“b”、“c”的列表操作
回答by Kipton Barros
Have a look at the ScalaDoc for Seq,
看看Seq的 ScalaDoc ,
scala> dirty.distinct
res0: List[java.lang.String] = List(a, b, c)
Update. Others have suggested using Setrather than List. That's fine, but be aware that by default, the Setinterface doesn't preserve element order. You may want to use a Set implementation that explicitly doespreserve order, such as collection.mutable.LinkedHashSet.
更新。其他人建议使用Set而不是List. 这很好,但请注意,默认情况下,Set界面不保留元素顺序。您可能需要使用一组实施,明确并维持秩序,如collection.mutable.LinkedHashSet。
回答by crockpotveggies
scala.collection.immutable.Listnow has a .distinctmethod.
scala.collection.immutable.List现在有一个.distinct方法。
So calling dirty.distinctis now possible without converting to a Setor Seq.
因此dirty.distinct,现在可以在不转换为 aSet或 的情况下进行调用Seq。
回答by paradigmatic
Before using Kitpon's solution, think about using a Setrather than a List, it ensures each element is unique.
在使用 Kitpon 的解决方案之前,请考虑使用 aSet而不是 a List,它确保每个元素都是唯一的。
As most list operations (foreach, map, filter, ...) are the same for sets and lists, changing collection could be very easy in the code.
由于大多数列表操作(foreach, map, filter, ...)对于集合和列表是相同的,因此在代码中更改集合可能非常容易。
回答by zentrope
Using Set in the first place is the right way to do it, of course, but:
当然,首先使用 Set 是正确的方法,但是:
scala> List("a", "b", "a", "c").toSet.toList
res1: List[java.lang.String] = List(a, b, c)
Works. Or just toSetas it supports the SeqTraversableinterface.
作品。或者就像toSet它支持序列Traversable界面。
回答by Sumit Pal
inArr.distinct foreach println _
inArr.distinct foreach println _
回答by Farquad
The algorithmic way...
算法方式...
def dedupe(str: String): String = {
val words = { str split " " }.toList
val unique = words.foldLeft[List[String]] (Nil) {
(l, s) => {
val test = l find { _.toLowerCase == s.toLowerCase }
if (test == None) s :: l else l
}
}.reverse
unique mkString " "
}

