-2

I have a vector of option of List of Tuple like

val x = Vector(
Some(List(("x",2))),
Some(List(("x",2),("y",3))),
None,
Some(List(("x",2),("z",2))),
Some(List(("x",2),("z",2))),
None)

How to get the list from the above vector

Updated:

The final purpose is to get the total count of element in the list (we have three element only x or y or z).

like total count of x would return 8 and total count of y would return 3 and total count of z would return 4

like

val totalx = x.flatten.filter ....  
dbc
  • 104,963
  • 20
  • 228
  • 340

2 Answers2

0

Sorry i got the answer

x.flatten.flatten.filter(x => x._1 == "y").map(x => x._2).sum

used flatten to remove the none and then used flatten again to get all tuple flatten then filter and summing up

0
x.flatMap {
  case Some(l) => l.filter(_._1=="x").map(_._2)
  case None => List(0)}.sum
Arnon Rotem-Gal-Oz
  • 25,469
  • 3
  • 45
  • 68
  • Can you provide some explanation how this solves the OP's problem. [Explaining entirely code-based answers](https://meta.stackoverflow.com/q/392712/3124333) – SiKing Apr 20 '23 at 21:54
  • Yes - but it is pretty self-explanatory. Map over the outer list when there's a list map over that while filtering the needed tuples and taking their values, flatten the results, and sum the resulting list – Arnon Rotem-Gal-Oz Apr 22 '23 at 08:23