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:


Lists:
* Lists
* Iterating over elements in a list

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap