Iterating circular way

后端 未结 4 1352
甜味超标
甜味超标 2021-01-11 11:14

I need iterate through a List but circular way. I need too add new elements to the list and iterate over all elements (olds and news elements), How I do it? Is there any dat

4条回答
  •  孤城傲影
    2021-01-11 11:48

    One option is to use the Stream class to create a lazy, circular, infinite sequence:

    scala> val values = List(1, 2, 3)
    values: List[Int] = List(1, 2, 3)
    
    scala> Stream.continually(values.toStream).flatten.take(9).toList
    res2: List[Int] = List(1, 2, 3, 1, 2, 3, 1, 2, 3)
    

    or this way:

    val values = List(1, 2, 3)
    
    def circularStream(values: List[Int],
                       remaining: List[Int] = List()): Stream[Int] = {
    
      if (remaining.isEmpty)
        circularStream(values,values)
      else
        Stream.cons(remaining.head, circularStream(values, remaining.drop(1)))
    }
    
    circularStream(values).take(9).toList //Same result as example #1
    

提交回复
热议问题