我喜欢这两个解决方案,但在这里是第一个解决的轻微改善的版本,我很喜欢:
class Slicer implements Iterator {
private List backingList
private int sliceSize
private int index
Slicer(List backingList, int sliceSize) {
this.backingList = backingList;
int ss = sliceSize;
// negitive sliceSize = -N means, split the list into N equal (or near equal) pieces
if(sliceSize < 0) {
ss = -sliceSize;
ss = (int)((backingList.size()+ss-1)/ss);
}
this.sliceSize = ss
}
Object next() {
if (!hasNext()) {
throw new NoSuchElementException()
}
def ret = backingList.subList(index, Math.min(index+sliceSize , backingList.size()));
index += sliceSize
return ret
}
boolean hasNext() {
return index < backingList.size() - 1
}
void remove() {
throw new UnsupportedOperationException() //I'm lazy ;)
}
List asList() {
this.collect { new ArrayList(it) }
}
List flatten() {
backingList.asImmutable()
}
}
// ======== TESTS
def a = [1,2,3,4,5,6,7,8];
assert [1,2,3,4,5,6,7,8] == a;
assert [[1, 2], [3, 4], [5, 6], [7, 8]] == new Slicer(a,2).asList();
assert [[1,2,3], [4,5,6], [7,8]] == (new Slicer(a,3)).collect { it } // alternative to asList but inner items are subList
assert [3, 2, 1, 6, 5, 4, 8, 7] == ((new Slicer(a,3)).collect { it.reverse() }).flatten()
// show flatten iterator
//new Slicer(a,2).flattenEach { print it }
//println ""
// negetive slice into N pieces, in this example we split it into 2 pieces
assert [[1, 2, 3, 4], [5, 6, 7, 8]] == new Slicer(a,-2).collect { it as List } // same asList
assert [[1, 2, 3], [4, 5, 6], [7, 8]] == new Slicer(a,-3).asList()
//assert a == (new Slicer(a,3)).flattenCollect { it }
assert [9..10, 19..20, 29..30] == ((new Slicer(1..30,2)).findAll { slice -> !(slice[1] % 10) })
assert [[9, 10], [19, 20], [29, 30]] == ((new Slicer(1..30,2)).findAll { slice -> !(slice[1] % 10) }.collect { it.flatten() })
println((new Slicer(1..30,2)).findAll { slice -> !(slice[1] % 10) })
println((new Slicer(1..30,2)).findAll { slice -> !(slice[1] % 10) }.collect { it.flatten() })
可能重复的[Groovy的内置分割的阵列划分为相等大小的子阵列?](http://stackoverflow.com/questions/2924395/groovy-built-in-to-split-an-array -into-equal-sized-subarrays) – 2011-05-03 18:24:18
我同意这不是一个确切的重复,因为你寻找的是懒惰的本质。 – 2011-05-04 02:34:35
我不会称之为片,而是整理。我认为切片是更像这样的:http://www.webquills.net/web-development/perl/perl-5-hash-slices-can-replace.html – 2017-09-11 17:20:01