Suppose I have x: List[A]
. What is an elegant way of building y: List[A]
such that y
contains only the first occurrence of each element of x
, in the same order? Actually I am really only interested in the case A=Int
but if there is a general solution, even better.
Asked
Active
Viewed 136 times
1

mitchus
- 4,677
- 3
- 35
- 70
-
http://stackoverflow.com/questions/1538598/how-in-scala-to-find-unique-items-in-list – cyon May 21 '13 at 14:49
-
2scala> List(1,2,3,2,4).distinct res0: List[Int] = List(1, 2, 3, 4) – twillouer May 21 '13 at 14:54
-
@cyon : that question does not ask to preserve the initial order, and although there are some answers that seem to preserve it, I was wondering whether there was something more elegant. – mitchus May 21 '13 at 15:01
-
@twillouer Is `distinct` guaranteed to preserve the initial order? – mitchus May 21 '13 at 15:02
1 Answers
2
As correctly suggested by twillouer, use the .distinct
method. It guarantees to preserve the order you expect.

Nikita Volkov
- 42,792
- 11
- 94
- 169
-
Thanks for the link! I agree that the current implementation guarantees order preservation, but is it part of the method's "contract", or could it change in future versions of the collections library? (Also, do you know if I am supposed to delete my question?) – mitchus May 21 '13 at 16:23
-
@mitchus You can consider everything said in method documentation to be its contract. I can't predict the future, but that kind of change is highly unlikely since the algorithm is pretty standard, and it would only be allowed in a major release (i.e., not in `2.10.x`), since it would break the compatibility. You should not delete your question unless you believe it is a duplicate or [inappropriate in any other way](http://stackoverflow.com/faq#questions). – Nikita Volkov May 21 '13 at 16:35