Filtering Seq Tuple3 using one element of each Tuple

I have Seqitems Tuple3. I need a resulting collection (possibly Set) consisting of the second element of each tuple.

for instance

(a, b, c), (d, e, f), (g, h, i) ==> (b, e, h)

Any idea? I searched a lot, but everything I find is related to filtering on tuples, and not inside them, if that makes sense.

I'm still new to Scala, learning is a lengthy process :) Thanks for all your help.

+3
source share
3 answers

yourSeqOfTuples.map(tuple => tuple._2).toSetwhich can be reduced to yourSeqOfTuples.map(_._2).toSet

If you prefer this, you can use {} rather than (). _2is a method that gets the second element of a tuple.

+3
source

, , - Seq[(A, B, C)] => Set[B], , . ,

scala> Seq(('a', "foo", 1), ('b', "bar", 2)).map(_._2).toSet
res0: scala.collection.immutable.Set[java.lang.String] = Set(foo, bar)
+6

If you don't like awkward accessors (_1, _2, etc.), a β€œpartial function literal” in which you can use pattern matching:

scala> Seq(('a', "foo", 1), ('b', "bar", 2)) map { case (_, x, _) => x } toSet
res1: scala.collection.immutable.Set[java.lang.String] = Set(foo, bar)
+4
source

All Articles