如何计算scala中元组中字符串的长度

时间:2017-12-08 07:10:54

标签: scala scala-collections

给定一个元组列表,其中元组的第一个元素是一个整数,第二个元素是一个字符串,

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))

我想打印相应字符串长度为4的数字。

这可以在一行中完成吗?

5 个答案:

答案 0 :(得分:2)

您需要.collect,即过滤器+地图

根据您的意见,

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))

过滤长度为4的那些

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

使用filter + map

的替代解决方案
scala> input.filter { case(number, string) => string.length == 4 }
            .map { case (number, string) => number}
res4: List[Int] = List(2, 4, 5)

答案 1 :(得分:1)

filterprint如下

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

您应该输出

2
4
5

答案 2 :(得分:1)

我喜欢使用收集的@prayagupd回答。但 foldLeft 是我在Scala中最喜欢的功能之一!你可以使用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)

答案 3 :(得分:0)

使用for comprehension如下,

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

以上示例提供

List(2, 4, 5)

注意我们模式匹配并提取每个元组中的元素并按字符串大小过滤。要打印列表,请考虑例如aList.foreach(println)

答案 4 :(得分:0)

这可以做到:

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

在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>