[2.0.x-java] ordering of a LinkedHashMap

90 views
Skip to first unread message

Michi Gysel

unread,
Oct 19, 2012, 1:30:04 PM10/19/12
to play-fr...@googlegroups.com
Hi all

I've got a question regarding Scala Templates in combination the the java.util.LinkedHashMap.

My controller code:

List<Category> categories = Category.all(); // .all() is sorted by category.name asc
Map<Category, List<Run>> runsByCategory = new LinkedHashMap<Category, List<Run>>();
for (Category category : categories) {
    runsByCategory.put(category, Run.findAllDescByCategory(category.id));
}

My template code:

@for( (category, runs) <- runsByCategory) {

    <h2>@category.name</h2>

}

The interesting thing is that play is printing the category names in descending order. I'm really sure that the ordering in the Java part is correct.

Can somebody explain why the Scala for block seems to reverse the order?

Kind Regards
Michi Gysel

Stephane C

unread,
Oct 19, 2012, 3:00:44 PM10/19/12
to play-fr...@googlegroups.com
Hello,

I had a similar issue a while ago, my linkedhashmaps losed order when used in scala templates.
After many hours googling for a solution, I learned that this had to do with "glue" that translate java maps to their scala equivalent.

Found some tips here :

But nothing seemed to work (I recognize I did not try very hard) and due to deadlines approaching, I chose to extract the keys in a list and used it as loop argument. 

If you find something, please let me know!
Best

virtualeyes

unread,
Oct 19, 2012, 4:09:32 PM10/19/12
to play-framework
If it's Scala in the template layer and you LHMap is getting silently
converted to a Scala immutable Map, you could try:
@import scala.collection.immutable.ListMap
@ListMap( categories.toList.sortBy(_._1):_* )

or, break that bit out if you're going to need proper sorting
application-wide (one would assume so ;-))

// views/utils/Foo.scala
object FooUtils {
class MapSort(m: Map[String,String]) {
import scala.collection.immutable.ListMap
def keySort = ListMap( m.toList.sortBy(_._1):_* )
}
@inline implicit final def sortedMap(m: Map[String,String]) = new
MapSort(m)
}

and then in your views:
@import views.utils.FooUtils._
@categories.keySort

Of course, not sure if any of this applies to Play Java, so FWIW...
Reply all
Reply to author
Forward
0 new messages