How to split a sequence into two pieces by predicate?

后端 未结 6 947
孤城傲影
孤城傲影 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:21

    I know I might be late for the party and there are more specific answers, but you could make good use of groupBy

    val ret = List(1,2,3,4).groupBy(x => x % 2 == 0)
    
    ret: scala.collection.immutable.Map[Boolean,List[Int]] = Map(false -> List(1, 3), true -> List(2, 4))
    
    ret(true)
    res3: List[Int] = List(2, 4)
    
    ret(false)
    res4: List[Int] = List(1, 3)
    

    This makes your code a bit more future-proof if you need to change the condition into something non boolean.

提交回复
热议问题