1

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.

3 Answers 3

3

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()
Sign up to request clarification or add additional context in comments.

Comments

1

You also need to convert the inner List[Int]:

parentList.asScala.flatMap(_.asScala)

Comments

0

Try like this

import scala.jdk.CollectionConverters._
parentList.asScala.flatMap.map(_.toSeq)

This will do the trick.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.