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 Accessing element at ith Index from ArrayList ) to iterate a list. Warning: this approach is inefficient for linked lists.