Convertin List to Set in Scala

Viewed 2340

I need to convert the list to set but in order. But I am getting the set that is not in order.

def toset(list: List[Int]): Int = {
    var newset = Set.empty[Int]
    for (i <- list){
      newset += i
    }
}

Then, if I do list = List[Int] (4,6,2,1,7) and toset(list), I will get newset = Set(1,6,2,7,4) instead of newset = Set (4,6,2,1,7)

2 Answers

You can use LinkedHashSet. It is ordered (not sorted) Set type that pertains the insertion order.

Also in Scala you don't need a traditional for loop to convert between collection types. You can just use to(Factory) method like:

val list = List(4,6,2,1,7)
list.to(collection.mutable.LinkedHashSet)
//Returns LinkedHashSet(4,6,2,1,7)

You can technically use the immutable.ListSet too, but it is proven to be inefficient at this moment (See here)

Set are unordered collections by definition.

If you want a sorted Set you need to use the SortedSet Class, but it will sort the elements by an implicit sorting function depending on the element types. It wont keep the original list order:

    val list = List[Int] (4,6,2,1,7)
    list: List[Int] = List(4, 6, 2, 1, 7)
    
    collection.SortedSet(list:_ *)
    res2: scala.collection.SortedSet[Int] = TreeSet(1, 2, 4, 6, 7)
Related