Search code examples
scalatemplatesplayframework-2.0multimap

Play scala template with google Multimap


I have a Multimap object from com.google.common.collect.Multimap. How can i iterate throught this Multimap in my Play scala template ?

@if(!googleMultimapObject.isEmpty()){

for ...

}

Thanks.


Solution

  • First import JavaConverters at the top of your template (i.e. second line, not the signature)

    @import scala.collection.JavaConverters._
    

    This will supply asScala methods to your java collections. via an implicit.

    Now you can do this:

    @for(entry <- googleMultimapObject.entries.asScala) {
      <p>@entry.getKey()</p>
      <p>@entry.getValue()</p>
    }
    

    Alternatively, to list the values for each key, you can do this:

    @for((key, values) <- googleMultimapObject.asMap.asScala) {
      <p>key: @key</p>
      <p>
      @for (value <- values.asScala) {
        <span>@value</span>
      }
      </p>
    }
    

    There's a shortcut happening here to unpack the key and values: .asMap.asScala gives us a scala map. When you iterate a scala map, you get tuples of (KeyType, ValueType). The above syntax unpacks the tuple into (key, values)