Iterate Set to streamline the Play Framework

I am passing my template a TreeSet using Strings . However, when I loop over a set like this:

 @(usernames : TreeSet[String]) @for( name <- usernames){ @name , } 

However, names are never printed in the correct order.

How can I iterate over my set in my template and print the names in order?

+4
source share
2 answers

This is due to the way Scala Templates works. I suspect that your TreeSet collection is under the hood mapped to another collection and as a result the ordering is not preserved.

Obviously, there is a difference between the behavior of the Scala for loop and the for loop in Scala patterns. If you run your code as normal Scala code, the order of the TreeSet is obviously preserved:

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

One way to solve the problem is to use an iterator in a Scala template:

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

or convert a TreeSet to a sequence:

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

There is no guaranteed order for any Set class, so it’s best to sort it before repeating.

If you want to print them in alphabetical order, you must convert it to a list and then repeat

 @(usernames : TreeSet[String]) @for( name <- usernames.toList().sortWith(_ < _)){ @name , } 
+2
source

All Articles