How to implement 'takeUntil' of a list?

后端 未结 6 1094
傲寒
傲寒 2021-01-05 01:52

I want to find all items before and equal the first 7:

val list = List(1,4,5,2,3,5,5,7,8,9,2,7,4)

My solution is:



        
6条回答
  •  甜味超标
    2021-01-05 02:39

    Some ways by use built-in functions:

    
    val list = List(1, 4, 5, 2, 3, 5, 5, 7, 8, 9, 2, 7, 4)
    //> list  : List[Int] = List(1, 4, 5, 2, 3, 5, 5, 7, 8, 9, 2, 7, 4)
    //Using takeWhile with dropWhile
    list.takeWhile(_ != 7) ++ list.dropWhile(_ != 7).take(1)
    //> res0: List[Int] = List(1, 4, 5, 2, 3, 5, 5, 7)
    //Using take with segmentLength
    list.take(list.segmentLength(_ != 7, 0) + 1)
    //> res1: List[Int] = List(1, 4, 5, 2, 3, 5, 5, 7) //Using take with indexOf list.take(list.indexOf(7) + 1) //> res2: List[Int] = List(1, 4, 5, 2, 3, 5, 5, 7)

提交回复
热议问题