简体   繁体   中英

printing length of string of Tuples in Scala

I am a newbie to Scala. I have a Tuple[Int, String]

((1, "alpha"), (2, "beta"), (3, "gamma"), (4, "zeta"), (5, "omega"))

For the above list, I want to print all strings where the corresponding length is 4.

printing length of string of Tuples in Scala

val tuples = List((1, "alpha"), (2, "beta"), (3, "gamma"), (4, "zeta"), (5, "omega"))
println(tuples.map(x => (x._2, x._2.length)))
//List((alpha,5), (beta,4), (gamma,5), (zeta,4), (omega,5))

I want to print all strings where the corresponding length is 4

You can filter first and then print as

val tuples = List((1, "alpha"), (2, "beta"), (3, "gamma"), (4, "zeta"), (5, "omega"))
tuples.filter(_._2.length == 4).foreach(x => println(x._2))

it should print

beta
zeta

You can convert your Tuple to List and then map and filter as you need:

tuple.productIterator.toList
.map{case (a,b) => b.toString}
.filter(_.length==4)

Example:

For the given input:

 val tuple = ((1, "alpha"), (2, "beta"), (3, "gamma"), (4, "zeta"), (5, "omega"))
tuple: ((Int, String), (Int, String), (Int, String), (Int, String), (Int, String)) = ((1,alpha),(2,beta),(3,gamma),(4,zeta),(5,omega))

Output:

List[String] = List(beta, zeta)

Let's suppose you have a list of Tuple, and you need all the values with string length equal to 4.

You can do a filter on the list:

val filteredList = list.filter(_._2.length == 4)

And then iterate over each element to print them:

filteredList.foreach(tuple => println(tuple._2))

Here is way to achieve this

scala> val x = ((1, "alpha"), (2, "beta"), (3, "gamma"), (4, "zeta"), (5, "omega"))
x: ((Int, String), (Int, String), (Int, String), (Int, String), (Int, String)) = ((1,alpha),(2,beta),(3,gamma),(4,zeta),(5,omega))

scala> val y = x.productIterator.toList.collect{
  case ele : (Int, String) if ele._2.length == 4 => ele._2
}
y: List[String] = List(beta, zeta)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM