Lobsterrrr Lobsterrrr - 3 months ago 8
Scala Question

Extract the n-th elements from sublists of list and combine them in a new list?

Given

List[List[Any]]
, how can I reduce it to
List[Any]
that would contain n-th elements of each sublist?
Let me explain it with an example. This is the initial list:

List(List(1,2,3,44),List(2,3,4,55))


I want to extract 4-th elements from
List(1,2,3,44)
and
List(2,3,4,55)
in order to get:

List(44,55)


Should Ithe use
reduce
or should I combine
map
with
flatten
or something? Any hint would be very useful.

elm elm
Answer

Lift each sublist to a partial function, where list positions not defined are mapped to None, and defined positions to Some(listValue), and use flatMap to flatten out onto a list,

xs.flatMap(_.lift(3))
res1: List[Int] = List(44, 55)

xs.flatMap(_.lift(4))
res2: List[Int] = List()
Comments