Is there an easy way to convert a comma delimited String into a LinkedHashSet in Scala? The goal is to remove duplicates in the string, but it needs a FOR loop. So I thought I could just split the String into a collection like LinkedHashSet that can preserve the original order and also remove duplicates. I did some research, but didn't find a way. So just want to confirm here if it's feasible.
For example, for String:
aaa, bbb, ccc, aaa, ddd
I want to make the to be:
aaa, bbb, ccc, ddd
Thanks
答案 0 :(得分:4)
您真的不需要0
。 Scala集合有方便的方法LinkedHashSet
:
distinct
产地:
"aaa, bbb, ccc, aaa, ddd".split(", ").distinct.mkString(", ")
答案 1 :(得分:3)
It is as simple as this:
import scala.collection.mutable.LinkedHashSet
scala> "aaa, bbb, aaa, ccc, ddd".split(", ").to[LinkedHashSet]
res12: scala.collection.mutable.LinkedHashSet[String] = Set(aaa, bbb, ccc, ddd)
you could use ListSet
that is immutable as well, although set will be in reverse order
scala> import scala.collection.immutable.ListSet
scala> "aaa, bbb, aaa, ccc, ddd".split(", ").to[ListSet]
res0: scala.collection.immutable.ListSet[String] = ListSet(ddd, ccc, bbb, aaa)
scala> res0.toList.reverse
res1: List[String] = List(aaa, bbb, ccc, ddd)