【问题标题】:searching on a List Of Case Class在案例类别列表中搜索
【发布时间】:2014-11-19 00:15:01
【问题描述】:

我需要在案例类别列表中进行搜索 示例:在下面的示例中,我想知道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))

【问题讨论】:

    标签: scala collections scala-collections case-class


    【解决方案1】:

    你可以使用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))
    

    【讨论】:

      【解决方案2】:
      scala> teamList.filter(t => t.name == "php")
      res0: List[Team] = List(Team(php,elephant.jpg,5800,8))
      

      【讨论】:

        【解决方案3】:

        您可以使用函数式编程来为这类事情提供良好的语法:

        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
        

        【讨论】:

        • 我可以得到它包含或不包含的布尔值吗?
        • @GovindSinghNagarkoti:您可以按照我的回答中所述使用exists
        • @tuxdna : 没错,我查文档太快了,没看到。
        • @Dici:我很高兴能帮上忙 :-)
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-02
        • 1970-01-01
        相关资源
        最近更新 更多