Вопрос

I have a Seq of Tuple3 elements. I want a resulting collection (probably a Set) made up with the second element of each tuple.

For example

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

Any idea? I searched a lot but all I'm finding has to do with filtering on the tuples, not within them, if that makes any sense.

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

Это было полезно?

Решение

yourSeqOfTuples.map(tuple => tuple._2).toSet, which may be shortedned to yourSeqOfTuples.map(_._2).toSet

You may use {} rather than () if you prefer it so. _2 is the method which gets the second element of the tuple.

Другие советы

From your description of what you want, which is some function of type Seq[(A, B, C)] => Set[B], you need to map, rather than filter. For example,

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

If you don't like the clumsy tuple accessors (_1, _2, etc.), a "partial function literal" where 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)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top