loops - groovy 中的 reverse() 方法仅仅是迭代的抽象吗?

标签 loops groovy iteration

基于 question ,用户希望访问 100000 行文件的第 99999 行,而无需使用 eachLine 进行迭代。关闭第一个 99998 行。所以,我建议他使用
file.readLines().reverse()[1]访问文件的第 99999 行。

这在逻辑上对程序员有吸引力。但是,我对这种方法的实现的复杂性非常怀疑。

reverse()方法仅仅是对程序员隐藏的行上的完整迭代的抽象,或者它是否真的像能够迭代尽可能少的行以达到所需的行一样聪明?

最佳答案

如您所见 from the code , reverse()电话Collections.reverse在 Java 中反转列表。

然而,非变异代码为您提供了另一种选择。使用 listIterator()你可以用 hasPrevious 得到一个迭代器和 previous返回列表,如果你这样做:

// Our list
def a = [ 1, 2, 3, 4 ]
// Get a list iterator pointing at the end
def listIterator = a.listIterator( a.size() )
// Wrap the previous calls in another iterator
def iter = [ hasNext:{ listIterator.hasPrevious() },
             next:{ listIterator.previous() } ] as Iterator

然后我们可以这样做:
// Check the value of 1 element from the end of the list
assert iter[ 1 ] == 3

但是,所有这些都是底层的 ArrayList,因此如果您这样做,它几乎肯定会更快(并且更容易阅读代码):
assert a[ 2 ] == 3

而不是所有的逆转。虽然很明显,这需要分析以确保我是对的......

关于loops - groovy 中的 reverse() 方法仅仅是迭代的抽象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11644961/

相关文章:

javascript - 如何遍历 h1 元素并使每个单词使用 jquery 淡入淡出?

java - 使用 spock 对 Spring Cloud Gateway 过滤器进行单元测试

hibernate - 获取一个懒惰的一对多列表的 child

java - 在Java中可以使用迭代来生成字符串吗?

c++ - 如何在 STL map 内迭代 STL map ?

c - 从链表 (C) 打印值时出现段错误

javascript - 循环中暂停并重新启动setTimeout

python - 类型错误: 'float' 对象不可迭代,Python 列表

multithreading - Groovy GPars如何按线程号/计数休眠线程?

python - 简化 pandas 中大文件的处理