How in Scala to find unique items in List

前端 未结 8 891
既然无缘
既然无缘 2020-12-04 17:14

How in Scala to find unique items in List?

相关标签:
8条回答
  • 2020-12-04 17:59

    If you refer to the Rosetta Code: Create a Sequence of unique elements

    val list = List(1,2,3,4,2,3,4,99)
    val l2 = list.removeDuplicates
    // l2: scala.List[scala.Int] = List(1,2,3,4,99)
    

    Since List is immutable, you wont modify the initial List by calling removeDuplicates

    Warning: as mentioned by this tweet(!), this does not preserve the order:

    scala> val list = List(2,1,2,4,2,9,3)
    list: List[Int] = List(2, 1, 2, 4, 2, 9, 3)
    
    scala> val l2 = list.removeDuplicates
    l2: List[Int] = List(1, 4, 2, 9, 3)
    

    For a Seq, that method should be available in Scala2.8, according to ticket 929.
    In the meantime, you will need to define an ad-hoc static method as the one seen here

    0 讨论(0)
  • 2020-12-04 18:00

    In 2.8, it's:

    List(1,2,3,2,1).distinct  // => List(1, 2, 3)
    
    0 讨论(0)
提交回复
热议问题