Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preferred way to iterate a List except the first element

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?

like image 578
Evgeny Kharitonov Avatar asked Dec 22 '17 07:12

Evgeny Kharitonov


2 Answers

If you use Java 8 or above you can use:

column.stream().skip(1).forEach((c) -> System.out.println(c))
like image 154
senjin.hajrulahovic Avatar answered Oct 19 '22 10:10

senjin.hajrulahovic


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.

like image 44
GhostCat Avatar answered Oct 19 '22 11:10

GhostCat