Juh_
Juh_

Reputation: 15549

Convert list of sortedset to sortedset in scala

(Still new to scala) I have a List[SortedSet[A]], and I'd like a unique SortedSet[A] with all (unique and sorted) elements. How should I do that?

My goal is: I have a class, say Container, that contain a list of Element and a list of (sub)Container. This class should implement a recursive getSortedElements(): SortedSet[Element] methods.

So I easily have this invalid code:

case class Container(myElements: List[Element], myContainers: List[Container]){
    def getSortedElements(): SortedSet[Element] =
        SortedSet(myElements) ++ SortedSet(myContainers.map(_.getSortedElements))
}

Upvotes: 0

Views: 160

Answers (1)

childofsoong
childofsoong

Reputation: 1936

Scala's Set types already enforce uniqueness, so all you need to do is combine them:

val a = SortedSet(1,2,3)
val b = SortedSet(2,7,5)
val c = SortedSet(1, 9)
List(a, b, c).fold(SortedSet())((x, y) => x ++ y)

You can also use reduce instead of fold:

List(a, b, c).reduce((x, y) => x ++ y)

See Scala : fold vs foldLeft for more about the differences between those

Upvotes: 1

Related Questions