Filtering list of tuples - better readability

158 Views Asked by At

What is a good way( read better readability) to filter a list of tuples. I'm using

tupleList.filter(_._2).map(_._1)

But this does not feel readable.

2

There are 2 best solutions below

0
On

Not sure how much better but you can use collect:

tupleList.collect { case (true, x) => x }

and of course give x some meaningful name. If the first element is not a boolean you can even do something like:

tupleList.collect { case (x, y) if (cond) => y}

and give x and y meaningful names

0
On

Using the equivalent with partial functions can also help:

tupleList.filter { case (_, snd) => snd }
         .map { case (fst, _) => fst }

This should improve significantly when Dotty arrives with tuple unpacking.