Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate Set in order Play Framework

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?

like image 558
Aerus Avatar asked Apr 30 '13 19:04

Aerus


1 Answers

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 ,
}
like image 67
annagos Avatar answered Sep 29 '22 01:09

annagos