Alfredo Diaz
Alfredo Diaz

Reputation: 658

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.

Upvotes: 1

Views: 786

Answers (3)

Ivan Stanislavciuc
Ivan Stanislavciuc

Reputation: 7275

Try like this

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

This will do the trick.

Upvotes: 0

Marth
Marth

Reputation: 24812

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()

Upvotes: 3

Lee
Lee

Reputation: 144136

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

parentList.asScala.flatMap(_.asScala)

Upvotes: 1

Related Questions