Reputation: 315
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
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 Option
s also.
Upvotes: 13