Search code examples
scalacollectionsplayframeworkplayframework-2.3twirl

Order of elements shown in generated HTML doesn't match the order of the elements in the collection


I'm getting crazy in struggling to understand why is this happening: I have a collection (a immutable SortedSet) containing 6 integers, and I iterate on them via .map method to create my generated HTML. The elements in the HTML page always show in different order every time I reload the page.

Here's some excerpts from my template

@deltas = @{ scala.collection.SortedSet[Int]( -15, -10, -5, 5, 10, 15) }

     @*** More code here ***@

@Logger.debug("DELTAS="+deltas.toString())
@deltas.map { delta =>
<li>
  @Logger.debug("DELTA="+delta.toString())
  <a href="#">@{dist.toDouble.intValue + delta}&nbsp;km (@delta)</a>
</li>
}

I also tried to Log the output to the screen - see Logger - and as expected the elements are always shown in the correct order.

[debug] application - DELTAS=TreeSet(-15, -10, -5, 5, 10, 15)
[debug] application - DELTA=-15
[debug] application - DELTA=-10
[debug] application - DELTA=-5
[debug] application - DELTA=5
[debug] application - DELTA=10
[debug] application - DELTA=15

Now I can only say the issue must be in the template engine, but I'd like to know whether it is a bug (unlikely) or I just need to know something more about some tricky aspect of it (very likely).


Solution

  • Apparently it seems it has something to do with a template engine. I need to dig down more to find out a reason. At this moment I can suggest a solution to this problem by using collection's iterator.

    @for(delta <- deltas.iterator) {
    <li>
      <a href="#">@{dist.toDouble.intValue + delta}&nbsp;km (@delta)</a>
    </li>
    }
    

    You can also convert TreeSet to Seq which solves the problem too.

    Previous

    First clue before update:

    You can read this question to learn more about a SortedSet mapping

    SortedSet map does not always preserve element ordering in result?