listscala

List of first occurrences in original order


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.


Solution

  • As correctly suggested by twillouer in a comment, use the .distinct method. It guarantees to preserve the order you expect.

    Example

    List(1, 2, 3, 2, 4).distinct
    

    Result:

    List(1, 2, 3, 4)
    

    Scaladoc

    SeqLike.distinct

    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.