user3685285
user3685285

Reputation: 6566

Scala convert Iterable of Tuples to Array of Just Tuple._2

Say I have a Iterable[(Int, String)]. How do I get an array of just the "values"? That is, how do I convert from Iterable[(Int, String)] => Array[String]? The "keys" or "values" do not have to be unique, and that's why I put them in quotation marks.

Upvotes: 4

Views: 2078

Answers (4)

Sascha Kolberg
Sascha Kolberg

Reputation: 7152

In addition to the already suggested map you might want to build the array as you map from tuple to string instead of converting at some point as it might save an iteration.

import scala.collection

val values: Array[String] = iterable.map(_._2)(collection.breakOut)

Upvotes: 1

Kshitij Banerjee
Kshitij Banerjee

Reputation: 1748

iterable.map(_._2).toArray

_._2 : take out the second element of the tuple represented by input variable( _ ) whose name I don't care.

Upvotes: 4

prayagupadhyay
prayagupadhyay

Reputation: 31192

Simply map the iterable and extract the second element(tuple._2),

scala> val iterable: Iterable[(Int, String)] = Iterable((100, "Bring me the horizon"), (200, "Porcupine Tree"))
iterable: Iterable[(Int, String)] = List((100,Bring me the horizon), (200,Porcupine Tree))

scala> iterable.map(tuple => tuple._2).toArray
res3: Array[String] = Array(Bring me the horizon, Porcupine Tree)

Upvotes: 1

Tanjin
Tanjin

Reputation: 2452

Simply:

val iterable: Iterable[(Int, String)] = Iterable((1, "a"), (2, "b"))

val values = iterable.toArray.map(_._2)

Upvotes: 1

Related Questions