Iterate Set in order Play Framework

playframework-2.0, scala, templates

Solution

This has something to do with the way Scala Templates work. I suspect your TreeSet collection is under the hood mapped to a different collection and as a result the ordering is not preserved.

There is clearly a difference between the behavior of the Scala for loop and the for loop in Scala Templates. If you run your code as regular Scala code the order of the TreeSet is obviously preserved:

val users = TreeSet("foo", "bar", "zzz", "abc")    
for (user <- users) {
  println(user)
}

One of the ways to solve the problem is to use the iterator in the Scala Template:

@for(name <- usernames.iterator) {
  @name ,
}

or transform the TreeSet to a sequence:

@for(name <- usernames.toSeq) {
  @name ,
}

Problem

I pass my template a `TreeSet` with `Strings`. However, when I loop over the set like this: ``` @(usernames : TreeSet[String]) @for( name <- usernames){ @name , } ``` However, the names are never printed in the correct order. How can I iterate over my set in my template and print the names in order?

Original source