scalascala-java-interop

Flattening nested java lists in Scala


I am working in Scala with java libraries. One of these libraries returns a list of lists. I want to flatten the list.

Example:

import scala.collection.JavaConverters._
var parentList : util.List[util.List[Int]] = null
parentList = new util.ArrayList[util.List[Int]]

parentList.asScala.flatten // error

I have used asScala converter but I'm still meeting an error.


Solution

  • You need to call .asScala on every inner list :

    scala> parentList.asScala.map(_.asScala)
    res0: scala.collection.mutable.Buffer[scala.collection.mutable.Buffer[Int]] = ArrayBuffer()
    
    scala> parentList.asScala.map(_.asScala).flatten
    res1: scala.collection.mutable.Buffer[Int] = ArrayBuffer()
    

    Note that calling .map and then .flatten can be done in one step using .flatMap :

    scala> parentList.asScala.flatMap(_.asScala)
    res2: scala.collection.mutable.Buffer[Int] = ArrayBuffer()