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.
As correctly suggested by twillouer in a comment, use the .distinct
method. It guarantees to preserve the order you expect.
List(1, 2, 3, 2, 4).distinct
Result:
List(1, 2, 3, 4)
def distinct: Repr
Builds a new sequence from this sequence without any duplicate elements.
[…]
returns A new sequence which contains the first occurrence of every element of this sequence.