brandbir
brandbir

Reputation: 315

Converting List[List[Int]] to Set[Int] in Scala

Is it possible to convert a List containing inner lists of type Int to Set[Int] in Scala?

For example, is the following conversion possible:

-> List(List(0), List(1), List(2)) to Set(0, 1, 2)

If yes, can it be explained?

Upvotes: 0

Views: 1056

Answers (1)

Akos Krivachy
Akos Krivachy

Reputation: 4966

First you need to flatten the list then convert it to a set:

List(List(0), List(1), List(2)).flatten.toSet
res0: Set[Int] = Set(0, 1, 2)

So what does flatten do? When you have multiple nested collections inside of each other it reduces the nesting by one level. This is applicable to anything that's Traversable like for an example Options also.

Upvotes: 13

Related Questions