Groovy .collect与元素数限制

Mat*_*ley 5 java grails groovy

有没有办法使用groovy .collect方法,但只有源数组中的某个索引?

例如,如果您的源迭代器长度为100万且您的限制为100,那么最终将得到100个项目的数组.

Chr*_*orf 20

从Groovy 1.8.1开始,你也可以做到

list.take(100).collect { ... }
Run Code Online (Sandbox Code Playgroud)

take将返回列表中的前100个元素.


ici*_*lik 3

如果您正在使用任何实现的数据结构,java.util.List您可以collection.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
Run Code Online (Sandbox Code Playgroud)

  • @Matt你可能可以调用 `toList()` 或 `as List` 将其转换为列表 (2认同)