Adrian
Adrian

Reputation: 5681

How to split collection into elements with flatMap

I have this type of input:
List( (key1, List(1,2,3)), (key2, List(4,5)) )
and I want to remap it the following way:
List( (key1, 1), (key1, 2), (key1, 3), (key2, 4), (key2, 5) )

I cannot figure out how to split a list into elements and still keep the key.

Upvotes: 0

Views: 915

Answers (2)

glava
glava

Reputation: 36

I'm not sure what you tried but here is the simplest way I would do it:

val splitMe = List( (key1, List(1,2,3)), (key2, List(4,5)) )
splitMe.flatMap(v=> v._2.map(g => (v._1, g)))

Upvotes: 2

Lee
Lee

Reputation: 144136

val flattened = list.flatMap({ case (k, l) => l.map((k,_)) })

Upvotes: 11

Related Questions