搜索案例类列表

时间:2014-09-24 13:18:09

标签: scala collections scala-collections case-class

我需要搜索案例类列表 示例:在下面的示例中,我想知道teamList是否包含name=php

scala> case class Team(name: String, image: String, nMember: BigInt, nYear: BigInt)
defined class Team

scala> val teamList=List(Team("scala","s.jpg",58,5),Team("java","cup.jpg",5400,18),Team("php","elephant.jpg",5800,8))
teamList: List[Team] = List(Team(scala,s.jpg,58,5), Team(java,cup.jpg,5400,18), Team(php,elephant.jpg,5800,8))

3 个答案:

答案 0 :(得分:8)

您可以使用filter操作:

scala> case class Team(name: String, image: String, nMember: BigInt, nYear: BigInt)
defined class Team

scala> val teamList=List(Team("scala","s.jpg",58,5),Team("java","cup.jpg",5400,18),Team("php","elephant.jpg",5800,8))
teamList: List[Team] = List(Team(scala,s.jpg,58,5), Team(java,cup.jpg,5400,18), Team(php,elephant.jpg,5800,8))

scala> teamList.filter( _.name.contains("php") )
res0: List[Team] = List(Team(php,elephant.jpg,5800,8))

仅检查是否存在这样的元素:

scala> teamList.exists( _.name.contains("php") )
res5: Boolean = true

对于更复杂的匹配,您绝对可以进行case-match模式匹配。

scala> teamList.filter( _ match { case Team("php", _, _, _) => true case _ => false } )
res2: List[Team] = List(Team(php,elephant.jpg,5800,8))

答案 1 :(得分:1)

scala> teamList.filter(t => t.name == "php")
res0: List[Team] = List(Team(php,elephant.jpg,5800,8))

答案 2 :(得分:1)

你可以使用函数式编程为这类事物提供一个很好的语法:

val teamList=List(Team("scala","s.jpg",58,5),Team("java","cup.jpg",5400,18),Team("php","elephant.jpg",5800,8))
teamList.find(_.name == "php") // finds the first element verifying the predicate, if any
teamList.exists(_.name == "php") // returns true if such element exists, false otherwise
teamList.filter(_.name == "php") // finds all the elements verifying the predicate