Preferred way to iterate a List except the first element

Evgeny Kharitonov :

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:

  1. Using sublist:

    for (String s : column.subList(1, column.size())) {
        System.out.println(s);
    }
    
  2. Using ListIterator

    for (ListIterator<String> iter = column.listIterator(1); iter.hasNext(); ) {
        System.out.println(iter.next());
    }
    
  3. 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?

GhostCat salutes Monica 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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=473006&siteId=1