0

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?

1 Answer 1

13

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Exactly, I came up with the same solution. Thanks very much

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.