Reputation: 1107
I often need to iterate through a List starting at the second element. 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
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?
Upvotes: 16
Views: 10435
Reputation: 140457
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). 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.
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.
Upvotes: 5
Reputation: 3127
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. 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 (e.g. iterator, sublist, etc.)
Upvotes: 1
Reputation: 3191
If you use Java 8 or above you can use:
column.stream().skip(1).forEach((c) -> System.out.println(c))
Upvotes: 14