我确信有一种优雅/有趣的方式,但我只能想到一个或多或少复杂的递归解决方案.
改述:是否有任何标准的lib(集合)方法,也没有简单的组合来获取列表的第一个不同元素?
scala> val s = Seq(3, 5, 4, 1, 5, 7, 1, 2)
s: Seq[Int] = List(3, 5, 4, 1, 5, 7, 1, 2)
scala> s.takeWhileDistinct //Would return Seq(3,5,4,1), it should preserve the original order and ignore posterior occurrences of distinct values like 7 and 2.
Run Code Online (Sandbox Code Playgroud)
如果你想要它快速,那么
{ val hs = scala.collection.mutable.HashSet[Int]()
s.takeWhile{ hs.add } }
Run Code Online (Sandbox Code Playgroud)
会做的.(额外的牙箍可防止泄漏临时值hs.)