Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you replicate Clojure's (partition) or Scala's sliding() functions with Guava?

I have a list that I want to split in a manner similar to the (partition sz step col) method of Clojure or the IterableLike.sliding(size: Int, step: Int) function of Scala. Specifically, given a list like:

(1, 2, 3)

I want to be able to iterate over the sub-lists like:

(1, 2), (2, 3)

In Clojure this would be done with:

(partition 2 1 (1, 2, 3))

and with Scala it would be:

val it = Vector(1, 2, 3).sliding(2)

However I do not have such a luxury and I'm hoping to avoid having to roll my own. Guava has a partition method that comes close, but doesn't offer the overlap. Googling has been fruitless as well. Does such a method exist or will I have to roll my own?

like image 461
John S Avatar asked Jun 10 '12 03:06

John S


2 Answers

Guava does not have this, but its AbstractIterator will probably make "rolling your own" easier.

There might already be a feature request filed for it; if not, please feel free.

like image 117
Kevin Bourrillion Avatar answered Nov 09 '22 13:11

Kevin Bourrillion


Guava doesn't have anything like this right now, but if you file an issue, we can discuss adding it.

For myself, I would use an ArrayDeque to store the running window, but that wouldn't make sense for a library method.

like image 41
Louis Wasserman Avatar answered Nov 09 '22 13:11

Louis Wasserman