Iterating over elements in a list
suggest changeFor 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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents