简体   繁体   中英

scala iterate on subset of list

I am from a python world, doing some scala work, somebody help me on this. I have a start and end date, I created a date list with that like this,

def dateRange(from: DateTime, to: DateTime, step: Period) : Iterator[DateTime] = {
  Iterator.iterate(from)(_.plus(step)).takeWhile(!_.isAfter(to))
}

val from = new DateTime().withYear(2012).withMonthOfYear(1).withDayOfMonth(1)
val to = new DateTime().withYear(2018).withMonthOfYear(2).withDayOfMonth(1)
val step = new Period().withDays(1)

// Getting the iterative date lists
val range = dateRange(from, to, step)
val dateList = range.toList

val dates = dateList.map { p => p.toString("yyyy-MM-dd") }

However, now I need to iterate on this, however take only a subset of list elements every iteration.

Lets say, I have a list like this:

['2014-01-01','2014-01-02','2014-01-03','2014-01-04','2014-01-05','2014-01-06', ...]

For every iteration, I need to send 3 dates. How can I do this?

You can use: grouped on List:

list.grouped(3).toList

This will give you List[List[T]]

For example lets consider input to be:

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

After applying list.grouped(3).toList, output will be:

List(List(1,2,3),List(4,5,6), List(7,8))

Iterate over the list. This will do the needful

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM