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 data structure for them?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With