R.Gold
R.Gold

Reputation: 95

How to calculate length of string in a tuple in scala

Given a list of tuples, where the 1st element of the tuple is an integer and the second element is a string,

scala> val tuple2 : List[(Int,String)] = List((1,"apple"),(2,"ball"),(3,"cat"),(4,"doll"),(5,"eggs"))
tuple2: List[(Int, String)] = List((1,apple), (2,ball), (3,cat), (4,doll), (5,eggs))

I want to print the numbers where the corresponding string length is 4.

Can this be done in one line ?

Upvotes: 1

Views: 1412

Answers (5)

RAGHHURAAMM
RAGHHURAAMM

Reputation: 1099

This will do:

tuple2.filter(_._2.size==4).map(_._1)

In Scala REPL:

scala> val tuple2 : List[(Int,String)] = List((1,"apple"),(2,"ball"),(3,"cat"),(4,"doll"),(5,"eggs"))
tuple2: List[(Int, String)] = List((1,apple), (2,ball), (3,cat), (4,doll), (5,eggs))

scala> tuple2.filter(_._2.size==4).map(_._1)
res261: List[Int] = List(2, 4, 5)

scala>

Upvotes: 0

Sky
Sky

Reputation: 2609

I like @prayagupd answer using collect. But foldLeft is the one of my favourite function in Scala! you can use foldLeft:

  scala> val input : List[(Int,String)] = List((1,"apple"),(2,"ball"),(3,"cat"),(4,"doll"),(5,"eggs"))
   input: List[(Int, String)] = List((1,apple), (2,ball), (3,cat), (4,doll), (5,eggs))

  scala> input.foldLeft(List.empty[Int]){case (acc, (n,str)) => if(str.length ==4) acc :+ n  else acc}
   res3: List[Int] = List(2, 4, 5)

Upvotes: 1

elm
elm

Reputation: 20405

Using a for comprehension as follows,

for ((i,s) <- tuple2 if s.size == 4) yield i

which for the example above delivers

List(2, 4, 5)

Note we pattern match and extract the elements in each tuple and filter by string size. To print a list consider for instance aList.foreach(println).

Upvotes: 0

Ramesh Maharjan
Ramesh Maharjan

Reputation: 41957

you filter and print as below

tuple2.filter(_._2.length == 4).foreach(x => println(x._1))

You should have output as

2
4
5

Upvotes: 1

prayagupadhyay
prayagupadhyay

Reputation: 31192

you need .collect which is filter+map

given your input,

scala> val input : List[(Int,String)] = List((1,"apple"),(2,"ball"),(3,"cat"),(4,"doll"),(5,"eggs"))
input: List[(Int, String)] = List((1,apple), (2,ball), (3,cat), (4,doll), (5,eggs))

filter those of length 4,

scala> input.collect { case(number, string) if string.length == 4 => number}
res2: List[Int] = List(2, 4, 5)

alternative solution using filter + map,

scala> input.filter { case(number, string) => string.length == 4 }
            .map { case (number, string) => number}
res4: List[Int] = List(2, 4, 5)

Upvotes: 2

Related Questions