Search code examples
performancescalaoptimizationreview

Looking for the best solution


Consider this list composed of objects which are instances of case classes:

A, B, Opt(A),C, Opt(D), F, Opt(C), G, Opt(H)

I wan to normalize this list to get this result:

A, B, C, Opt(D), F, G, Opt(H)

As you see, if there are elements A and Opt(A) I replace them with just A or said other way, I have to remove OPT(A) element.

I would like:

  • most optimal solution in the mean of performance
  • shortest solution

Solution

  • This might be a little more concise, as filtering is what you want ;-):

    scala> List(1,2,3,Some(4),5,Some(5))
    res0: List[Any] = List(1, 2, 3, Some(4), 5, Some(5))
    
    scala> res0.filter {
         | case Some(x) => !res0.contains(x)
         | case _ => true
         | }
    res1: List[Any] = List(1, 2, 3, Some(4), 5)
    

    edit: For large collections it might be good to use a toSet or directly use a Set.