Iterating over elements in a list

suggest change

For the example, lets say that we have a List of type String that contains four elements: “hello, “, “how “, “are “, “you?”

The best way to iterate over each element is by using a for-each loop:

public void printEachElement(List<String> list){
    for(String s : list){
        System.out.println(s);
    }
}

Which would print:

hello,
how
are
you?

To print them all in the same line, you can use a StringBuilder:

public void printAsLine(List<String> list){
    StringBuilder builder = new StringBuilder();
    for(String s : list){
        builder.append(s);
    }
    System.out.println(builder.toString());
}

Will print:

hello, how are you?

Alternatively, you can use element indexing ( as described in http://stackoverflow.com/documentation/java/2989/lists/18794/accessing-element-at-ith-index-from-arraylist ) to iterate a list. Warning: this approach is inefficient for linked lists.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents