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?
If you use Java 8 or above you can use:
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). 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With