1

I have a class:

class Product {

    val productID = ...
    val weight = ...
    val size = ....

     .....[more fields]....

}

I have a List[Product] which contains the same product multiple times. How can I convert the list into a Set[Product] using productID as the 'unique' value so that each Product is only included once?

thanks

om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
Zuriar
  • 11,096
  • 20
  • 57
  • 92

1 Answers1

1

There is a standard way to do it:

val a = List(a1, a2...)

val as = a.toSet

If you mean that you have products with the same ID, but different, and you would be OK with picking whatever product, then you can do something like that:

val a = List(a1, a2...)
val a_ids = a map(_.productId) toSet

val products = a_ids.flatMap(id => a.find(_.productId == id))
Ashalynd
  • 12,363
  • 2
  • 34
  • 37