0

I am using play framework 2.3.8 and I need to iterate a java HashMap which I do like this in the template:

 @(city: String, intents: java.util.Map[Intent, TimeTable.Row], lang: Lang)

@for((item, index) <- intents.entrySet.zipWithIndex) {
            <li>Item @index </li>
        }

The problem now is that I got indexes as follows:

Item 7 Item 17 Item 22 Item 8 Item 28 Item 23 Item 33 Item 18 Item 5 Item 25 Item 11 Item 16

How is it possible to get ordered indices and why is the list here unordered?

dc10
  • 2,160
  • 6
  • 29
  • 46
  • 1
    You are trying to iterate using a Set, and it doesn't have any order in its elements. However you could change the type and order it by any inner property of the object. You can have a look at [this](http://stackoverflow.com/questions/2972871/how-to-sort-a-scala-collection-mapjava-lang-string-int-by-its-values) for a solution. – Carlos Vilchez Apr 28 '15 at 07:57
  • @CarlosVilchez Thanks, it clarifies is it, but how can I convert the java util map to a list which can be used with index inside the template? – dc10 Apr 28 '15 at 08:22
  • 1
    I don't think the template is the place for this type of tasks. I would convert it before sending it to the template to keep it simple. Do you really need to do it inside the template? – Carlos Vilchez Apr 28 '15 at 08:33
  • well we ended up using arraylist which does the increment properly – dc10 Apr 29 '15 at 12:30

2 Answers2

1

Just clarifing Carlos's comment

You could use implicit scala to java convertion:

@import scala.collection.JavaConversions._

@(city: String, intents: java.util.Map[Intent, TimeTable.Row], lang: Lang)

@for(((intent,row), index) <- intents.toList.zipWithIndex) {
    <li>Item @index : <strong>@intent</strong> <i>row</i></li>
}
Community
  • 1
  • 1
Odomontois
  • 15,918
  • 2
  • 36
  • 71
0

I recommend you to use SortedMap, and it's better not to transform your HashMap into something else inside the template, but use SortedMap from the start.