Java Groovy.collect的元素数限制
有没有一种方法可以使用groovyJava Groovy.collect的元素数限制,java,grails,groovy,Java,Grails,Groovy,有没有一种方法可以使用groovy.collect方法,但只能使用源数组中的某个索引 例如,如果源迭代器的长度为100万,限制为100,那么最终将得到100个项的数组。如果您使用的是实现java.util.List的任何数据结构,则可以在其上执行集合.subList(0,100)。其中0是开始索引,100是结束索引。然后将新集合传递到collect() 下面是一个使用扩展了java.util.Iterator的对象的示例: public class LimitIterator implement
.collect
方法,但只能使用源数组中的某个索引
例如,如果源迭代器的长度为100万,限制为100,那么最终将得到100个项的数组。如果您使用的是实现
java.util.List
的任何数据结构,则可以在其上执行集合.subList(0,100)
。其中0是开始索引,100是结束索引。然后将新集合传递到collect()
下面是一个使用扩展了java.util.Iterator
的对象的示例:
public class LimitIterator implements Iterator, Iterable {
private it
private limit
private count
LimitIterator(Iterator it, int limit) {
limit = limit;
count = 0;
it = it
}
boolean hasNext(){
return (count >= limit) ? false : it.hasNext()
}
Object next() {
if (!hasNext()) throw new java.util.NoSuchElementException()
count++
return it.next()
}
Iterator iterator(){
return this;
}
void remove(){
throw new UnsupportedOperationException("remove() not supported")
}
}
// Create a range from 1 to 10000
// and an empty list.
def list = 1..10000
def shortList = []
// Ensure that everything is as expected
assert list instanceof java.util.List
assert list.iterator() instanceof java.util.Iterator
assert list.size() == 10000
assert shortList instanceof java.util.List
// Grab the first 100 elements out of the lists iterator object.
for (i in new LimitIterator(list.iterator(), 100)) {
shortlist.add(i);
}
assert shortlist.size() == 100
您可以使用一系列索引来获取子列表,然后对子列表应用
collect
def result = list[0..100].collect { ... }
由于Groovy 1.8.1,您还可以
list.take(100).collect { ... }
where take将返回列表中的前100个元素。不幸的是,它不是list@Matt您可能可以调用
toList()
或as List
将其转换为列表我担心最终可能会将整个迭代器读入memory@Matt数组当前是如何存储的?@Matt您可以创建一个实现迭代器的包装器,并采用最大大小。take lazy是像Clojure中一样的,还是strict?我想在没有阅读代码的情况下采用(…)这是严格的。Lazy在Clojure这样的语言中非常好,因为它的数据结构是不可变的,而在Groovy中就不是这样了,因为Groovy中几乎所有的东西都是可变的。Lazy仍然可以很好,但作为默认值没有意义。这是一个对列表的操作,因此整个列表都将在内存中,因此它将是严格的,而不是像clojure中那样的Lazy。