How to split a sequence into two pieces by predicate?

后端 未结 6 946
孤城傲影
孤城傲影 2020-12-02 11:35

How do I split a sequence into two lists by a predicate?

Alternative: I can use filter and filterNot, or write my own method, but isn\'t th

6条回答
  •  星月不相逢
    2020-12-02 12:19

    You can also use foldLeft if you need something a little extra. I just wrote some code like this when partition didn't cut it:

    val list:List[Person] = /* get your list */
    val (students,teachers) = 
      list.foldLeft(List.empty[Student],List.empty[Teacher]) {
        case ((acc1, acc2), p) => p match {
          case s:Student => (s :: acc1, acc2)
          case t:Teacher  => (acc1, t :: acc2)
        }
      }
    

提交回复
热议问题