How in Scala to find unique items in List

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

How in Scala to find unique items in List?

8条回答
  •  一个人的身影
    2020-12-04 17:48

    Roll your own uniq filter with order retention:

    scala> val l = List(1,2,3,3,4,6,5,6)
    l: List[Int] = List(1, 2, 3, 3, 4, 6, 5, 6)
    
    scala> l.foldLeft(Nil: List[Int]) {(acc, next) => if (acc contains next) acc else next :: acc }.reverse
    res0: List[Int] = List(1, 2, 3, 4, 6, 5)
    

提交回复
热议问题