[英]Preferred way to iterate a List except the first element
I often need to iterate through a List starting at the second element. 我经常需要从第二个元素开始遍历List。 For example here is a column: 例如,这是一列:
List<String> column = Arrays.asList("HEADER", "value1", "value2", "value3");
I need to print only values. 我只需要打印值。
I see three approaches: 我看到三种方法:
Using sublist: 使用子列表:
for (String s : column.subList(1, column.size())) { System.out.println(s); }
Using ListIterator 使用ListIterator
for (ListIterator<String> iter = column.listIterator(1); iter.hasNext(); ) { System.out.println(iter.next()); }
Using index 使用索引
for (int i = 1; i < column.size(); i++) { System.out.println(column.get(i)); }
What is the most preferred one considering readability, best practices and performance? 考虑可读性,最佳实践和性能,最受欢迎的是什么?
In my opinion sublist solution is more readable, but I rarely saw it in practice. 在我看来,子列表解决方案更具可读性,但我很少在实践中看到它。 Does it have any significant deficiencies comparing to index solution? 与索引解决方案相比,它有任何重大缺陷吗?
如果您使用Java 8或更高版本,则可以使用:
column.stream().skip(1).forEach((c) -> System.out.println(c))
This really boils down to (almost) "personal style" only. 这真的归结为(几乎)“个人风格”。
You should simply pick what works best for you/your team. 您应该选择最适合您/您的团队的方法。
Option 3 seems to be the one that comes with the least overhead - options 1 and 2 both create new "intermediate" objects (the sublist respectively the iterator). 选项3 似乎是带有最少开销的选项 - 选项1和2都创建新的“中间”对象(子列表和迭代器)。 And just to be precise: sublist()
doesn't create a new list and populate that - it boils down to a new Sublist
object that simply "knows" about the boundaries within the larger parent list. 而且确切地说: sublist()
不会创建一个新列表并填充它 - 它归结为一个新的Sublist
对象,它只是“知道”较大父列表中的边界。
But : as soon as we consider lists that are not supporting random access to list elements (think linked lists for example) then option 3 results in a lot of performance cost compared to the others. 但是 :只要我们考虑不支持对列表元素的随机访问的列表(例如,想想链接列表),那么与其他元素相比,选项3会导致很多性能成本。
It's more a matter of personal preferences. 这更多的是个人喜好。 The sublist
method doesn't return a new object, just a view on top of the current list, so it doesn't have any memory overhead. sublist
方法不返回新对象,只返回当前列表顶部的视图,因此它没有任何内存开销。 I think the readability is the only criteria to decide about this and the last option is the most readable solution and doesn't need to call any extra method (eg iterator, sublist, etc.) 我认为可读性是决定这一点的唯一标准,最后一个选项是最易读的解决方案,不需要调用任何额外的方法(例如迭代器,子列表等)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.